在之前的代碼中,客戶端都是直接調(diào)用配置中心的server端來獲取配置文件信息。這樣就存在了一個(gè)問 題,客戶端和服務(wù)端的耦合性太高,如果server端要做集群,客戶端只能通過原始的方式來路由, server端改變IP地址的時(shí)候,客戶端也需要修改配置,不符合springcloud服務(wù)治理的理念。 springcloud提供了這樣的解決方案,我們只需要將server端當(dāng)做一個(gè)服務(wù)注冊到eureka中,client端去 eureka中去獲取配置中心server端的服務(wù)既可。
服務(wù)端改造
(1) 添加依賴
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
2) 配置文件
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/ ## 注冊中心eurka地址
這樣server端的改造就完成了。先啟動eureka注冊中心,在啟動server端,在瀏覽器中訪問: http://localhost:8761/ 就會看到server端已經(jīng)注冊了到注冊中心了。

image-20220102211013619.png
服務(wù)端改造
(1) 添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(2) 配置文件
server:
port: 9002
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
spring:
cloud:
config:
name: product
profile: dev
label: master
uri: http://localhost:8080
discovery:
enabled: true #從eureka中獲取配置中心信息
service-id: config-server
高可用
為了模擬生產(chǎn)集群環(huán)境,我們改動server端的端口為1000,再啟動一個(gè)server端來做服務(wù)的負(fù)載,提供 高可用的server端支持。

image-20220102211207803.png
如上圖就可發(fā)現(xiàn)會有兩個(gè)server端同時(shí)提供配置中心的服務(wù),防止某一臺down掉之后影響整個(gè)系統(tǒng)的 使用。
我們先單獨(dú)測試服務(wù)端,分別訪問: http://localhost:10000/product-pro.yml 、 http://localhost:10001/product-pro.yml 返回信息:
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
instance:
instance-id: ${spring.cloud.client.ip-address}:9002
preferIpAddress: true
productValue: 200
server:
port: 9002
spring:
application:
name: shop-service-product
datasource:
driver-class-name: com.mysql.jdbc.Driver
password: 111111
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
username: root
jpa:
database: MySQL
open-in-view: true
show-sql: true