前言
在SpringCloud之配置中心(config)的使用的基礎上加上SpringCloudBus實現配置文件動態更新
在此之前需要修改版本,否則會出現“Endpoint ID 'bus-env' contains invalid characters, please migrate to a valid format.”錯誤導致服務啟動失敗
springboot版本:
2.0.6.RELEASE
springcloud版本:
Finchley.SR2
由於使用bus中需要使用消息中間件來支持更新通知並且它支持RabbitMQ和Kfaka,所以還需要啟動其中之一,本文使用RabbitMQ,安裝使用可參考RabbitMQ的安裝(linux版)和RabbitMQ的安裝與基本使用(windows版)
config-server端
依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
<!-- 監控中心--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
配置文件
server.port=8050
spring.application.name=config-server
# 注冊到服務注冊中心
eureka.client.service-url.defaultZone=http://localhost:8090/eureka/
# github的倉庫地址
spring.cloud.config.server.git.uri=https://github.com/kurean/springconfig.git
# github的文件路徑
spring.cloud.config.server.git.searchPaths=repo
# github的分支,默認是master
spring.cloud.config.label=master
# 使用bus總線刷新配置文件 management.endpoints.web.exposure.include=bus-refresh //指定刷新地址 spring.cloud.bus.trace.enabled=true # 使用rabbitmq傳遞消息 spring.rabbitmq.host=192.168.184.130 spring.rabbitmq.port=5672 spring.rabbitmq.username=test //可以自己在rabbitmq的web管理頁面添加用戶,不添加則可以使用默認賬號guest spring.rabbitmq.password=123456 spring.rabbitmq.virtual-host=/vHost_test //不指定默認為/
config-client端
依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
配置文件application.properties
spring.application.name=config-client
server.port=9006
# 使用rabbitmq傳遞消息
spring.rabbitmq.host=192.168.184.130
spring.rabbitmq.port=5672
spring.rabbitmq.username=test
spring.rabbitmq.password=123456
spring.rabbitmq.virtual-host=/vHost_test
在使用遠程配置文件數據的地方加上@RefreshScope注解測試使用
@RestController @RefreshScope public class ConfigClientController { @Value("${cs.name}") String name; @Value("${cs.age}") String age; @GetMapping(value = "/hi") public String hi(){ return "我的名字是:"+name+",年齡是:"+age; } }
當git上的參數值修改后,需要利用消息總線觸發一個服務端configServer的/bus/refresh端點,而刷新所有客戶端的配置,所以發送請求http://localhost:8050/actuator/bus-refresh手動刷新配置中心,這樣就會通知所有的微服務進行修改校正從而達到不用自己手動重啟微服務重新讀取配置的目的,但是要注意的是這個請求必須是post請求,這里推薦使用postman調試接口工具
修改后配置服務端和客戶端日志:
動態刷新定點通知
其目的就是原先是無差別通知,如果想要定點通知某個微服務,那么就發送請求http://localhost:8050/actuator/bus-refresh/{destination},至於這個destination,則由微服務的服務名+端口號組成,比如http://localhost:8050/actuator/bus-refresh/config-client:9006則表示只通知config-client這個微服務進行配置修改