前言
在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这个微服务进行配置修改