Spring Cloud Bus将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。本文要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。
1、准备工作
需要装rabbitMq。
2、改造config-client
A.在pom文件加上起步依赖spring-cloud-starter-bus-amqp
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
B.application.properties中加上配置
RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码
sring.cloud.bus的三个配置:
spring.rabbitmq.host=
spring.rabbitmq.port=
spring.rabbitmq.username=
spring.rabbitmq.password=
spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh
C.ConfigClientApplication启动类代码如下
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RestController
@RefreshScope
public class ConfigClientApplication {
/**
* http://localhost:8881/actuator/bus-refresh
*/
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
3、我的测试
a.依次启动eureka-server、confg-cserver,启动两个config-client,端口为:8881、8882。
b.访问http://localhost:8881/hello 或者http://localhost:8882/hello 浏览器显示:
hello: adou
c.这时我们去代码仓库将name的值改为“amao”,即改变配置文件name的值。如果是传统的做法,需要重启服务,才能达到配置文件的更新。此时,我们只需要发送post请求:http://localhost:8881/actuator/bus-refresh,你会发现config-client会重新读取配置文件,再次访问
hello: amao
d.另外,/actuator/bus-refresh接口可以指定服务,即使用"destination"参数,比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服务名为customers的所有服务