Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。本文要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。
准备工作
官网上下载并安装RabbitMQ
修改config-client工程,并添加相关依赖
<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>
添加RabbitMQ相关配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh
服务启动类上增加@RefreshScope注解
@SpringBootApplication
@RestController
@RefreshScope
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
@Value("${userName}")
String userName;
@RequestMapping("/getUserName")
public String getUserName() {
return userName;
}
}
依次启动eureka-server、config-cserver,启动两个config-client,端口为:8881、8882
访问http://localhost:8881/getUserName或http://localhost:8882/getUserName 浏览器返回相同的值
soldier_123_willpan
去git远程仓库修改userName的值,传统做法需要重启config-client才能实现配置文件更新。
现在我们只需发送Post请求http://localhost:8881/actuator/bus-refresh或http://localhost:8882/actuator/bus-refresh,
通过Postman发送Post请求,config-client就会重新读取配置文件
注意:Springboot 2.0以后请求刷新由原来1.5X的http://localhost:8881/bus/refresh变成了http://localhost:8881/actuator/bus-refresh,启动类需加上注解@RefreshScope
然后我们再访问http://localhost:8882/getUserName,这时可以看到返回值已经变成了我们在git远程仓库修改后的配置
soldier_123_willpan_v2