在本地的一個案例中進行修改
修改微服務的相關pom文件
修改每個微服務的pom文件,添加SpringCloud提供的基於Consul的依賴
<!--SpringCloud提供的基於Consul的服務發現--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!--actuator用於心跳檢查--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
注:由於我之前的代碼是注冊到eureka中,把配置注解要刪了,pom的依賴還在,啟動直接報錯,還是要去掉的
<!--引入EurekaClient--> <!-- <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> -->
其中 spring-cloud-starter-consul-discovery 是SpringCloud提供的對consul支持的相關依賴。
spring-boot-starter-actuator 適用於完成心跳檢測響應的相關依賴。
配置服務注冊
server: port: 9001 #端口 spring: application: name: service-product #服務名稱 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: 123456 jpa: database: MySQL show-sql: true open-in-view: true ###開始配置consul的服務注冊 cloud: consul: host: 192.168.180.137 #consul服務器的主機地址 port: 8500 #consul服務器的ip地址 discovery: #是否需要注冊 register: true #注冊的實例ID (唯一標志) instance-id: ${spring.application.name}-1 #服務的名稱 service-name: ${spring.application.name} #服務的請求端口 port: ${server.port} #指定開啟ip地址注冊 prefer-ip-address: true #當前服務的請求ip ip-address: ${spring.cloud.client.ip-address}
server: port: 9002 #端口 spring: application: name: service-order #服務名稱 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: 123456 jpa: database: MySQL show-sql: true open-in-view: true ###開始配置consul的服務注冊 cloud: consul: host: 192.168.180.137 #consul服務器的主機地址 port: 8500 #consul服務器的ip地址 discovery: #是否需要注冊 register: true #注冊的實例ID (唯一標志) instance-id: ${spring.application.name}-1 #服務的名稱 service-name: ${spring.application.name} #服務的請求端口 port: ${server.port} #指定開啟ip地址注冊 prefer-ip-address: true #當前服務的請求ip ip-address: ${spring.cloud.client.ip-address}
其中 spring.cloud.consul 中添加consul的相關配置
host:表示Consul的Server的請求地址
port:表示Consul的Server的端口
discovery:服務注冊與發現的相關配置
instance-id : 實例的唯一id(推薦必填),spring cloud官網文檔的推薦,為了保證生成一個唯一的id ,也可以換成
${spring.application.name}:${spring.cloud.client.ipAddress}
prefer-ip-address:開啟ip地址注冊
ip-address:當前微服務的請求ip
在控制台中查看服務列表
打開ConsulServer的管理控制台,可以發現三個微服務已經全部注冊到Consul中了。
進行測試:
發現沒有問題。
由於第一次部署實在阿里雲上的,但是在服務檢查的時候一直顯示連接超時,可能網絡不帶好,換成自己的虛擬機就沒有問題。如下圖: