简介
Spring Cloud Bus
通过轻量级消息代理连接各个微服务,可以用来广播配置文件的更改,或者管理服务监控。它的一个核心思想是通过分布式的启动器对spring boot应用进行扩展,也可以用来建立一个多个应用之间的通信频道。目前唯一实现的方式是用AMQP
消息代理作为通道,同样特性的设置(有些取决于通道的设置)在更多通道的文档中。目前常用的有Kafka
和RabbitMQ
。
这里以RabbitMQ
为例进行测试。
环境准备
docker启动RabbitMQ
docker run -d --hostname my-rabbit --name pikachues-rabbit -p 5672:5672 -p15672:15672 rabbitmq:3-management
测试
这里以Springcloud配置中心之Spring Cloud Config基础进行测试。
添加依赖
给configclient_bus和configserver_bus都添加RabbitMQ依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
给configserver_bus添加actuator用于提供刷新接口
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置
给configclient_bus和configserver_bus都配置上rabbitmq,使之能连接上rabbitmq
spring:
rabbitmq:
username: guest
host: 安装rabbitmq的ip地址
password: guest
port: 5672
在configserver_bus中添加开启bus-refresh端点
management:
endpoints:
web:
exposure:
include: bus-refresh
由于configserver_bus给所有接口都添加了保护,所以刷新接口将无法直接访问,此时,可以通过修改Security
配置,对端点权限作出修改。
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
分别启动configserver_bus、configclient_bus,然后修改配置信息,提交到github,刷新client接口,查看是否有变化。
然后发送post请求:http://localhost:8081/actuator/bus-refresh
这个post请求是针对configserver-bus的,configserver-bus会把这个刷新指令传到rabbitmq,然后rabbitmq再把指定传给各个client。
这时候在configclient_bus的/hello
接口可以看到更新的配置数据。
逐个刷新
如果更新配置文件之后,不希望每一个微服务都去刷新配置文件,那么可以通过如下配置解决问题。
首先,给每一个configclient-bus添加instance-id:
eureka:
instance:
instance-id: ${spring.application.name}:${server.port}
为了更好的测试,对configclient-bus进行打包。
打包完成后,通过如下命令启动:
java -jar configclient_bus-0.0.1-SNAPSHOT.jar --server.port=8086
接下来就是修改配置文件,并且提交到github之后,可以通过如下方式只刷新某一个服务,例如只刷新8085的服务。
http://localhost:8081/actuator/bus-refresh/client1:8085