Bus 服务总线
Spring Cloud Bus 是轻量的消息代理,将分布式节点连接,用于广播配置文件的更新 或 监控管理
补充说明&优点
- Bus 是轻量级消息代理
- Bus 主要实现 配置的自动更新 (无需配置)
- Bus 底层基于 RabbitMQ实现
- 广播配置文件、监控管理
存在问题
上篇文章的 Config配置中心 启动后,此时更改 远端仓库 中某一微服务的配置文件,是不会同步本地缓存中的配置文件。因此在某一微服务运行后是不会及时更新配置文件,而是需要重启微服务才能更新生效
问题示例
- 以下主要展示 更改配置不会同步的问题
- 上篇章代码测试
- 修改仓库
user-service
微服务的配置文件user-dev.yml
添加test.name
属性 (用于测试)
依旧应用
user-service
进行测试
- 修改Controller
user-service
(在接口进行测试返回数据)
@RestController
@RequestMapping ("user")
public class UserController {
@Autowired
private UserService service;
@Value("${test.name}")
private String name;
@GetMapping ("name")
public String testConfig() {
return name;
}
//···
}
添加一个接口用于返回配置中的属性name的接口
- 运行测试1(查看刚刚在仓库中添加的属性)
依次启动Eureka
、config-server
、user-server
三个服务
访问 http://localhost:9091/user/name ,下图返回表示成功 - 修改仓库
user-service
微服务的配置文件user-dev.yml
主要修改test.name
属性的值
# 其他就不展示了
test :
name : Sanscan12
- 浏览器再次访问 http://localhost:9091/user/name
此时 配置中的
test.name
属性值没有更变
- 重启
user-service
微服务 ,再次访问http://localhost:9091/user/name
Git仓库中配置文件的修改并没有及时更新到 微服务,只有重启微服务才能生效
Bus应用
Bus 构架图
说明:
- 应用前提需要安装
RabbitMQ
才能实现功能 - 配置中心 需要自行暴露触发总线地址 /actuator/bus-refresh
- 请求 /actuator/bus-refresh 是固定的
- 当配置中心微服务接收到 /actuator/bus-refresh 请求时,向
RabbitMQ
发送配置改变消息,这时也会更新本地缓存 - 微服务 会监听
RabbitMQ
,如果坚监听到有仓库配置改变的消息,会重新读取本地缓存中的配置文件(实现不用重启提醒更新的效果)
应用示例
- 首先安装
RabbitMQ
,安装即可无需配置 config-server
添加 Bus依赖
<!-- Bus -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
config-server
添加配置application.yml
# ...
spring :
# ···
# 配置 rabbitmq信息,如果都是与默认值一致无需配置
rabbitmq :
host : localhost
port : 5672
username : guest
password : guest
management :
endpoints :
web :
exposure :
# 暴露触发消息总线的地址
# POST /actuator/bus-refresh
include : bus-refresh
消息总线的地址,主要用途在触发更新配置的请求!
user-service
添加依赖 Bus、监控管理
<!-- Bus 监听 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
user-service
添加配置bootstrap.yml
(配置与默认一致可跳过)
# ....
# 配置 rabbitmq信息,如果都是与默认值一致无需配置
rabbitmq :
host : localhost
port : 5672
username : guest
password : guest
user-service
修改UserController
添加注解@RefreshScope
@RestController
@RequestMapping ("user")
@RefreshScope // 自动刷新配置文件
public class UserController {
// ....
}
- 测试
- 依次启动
Eureka
、config-server
、user-server
三个服务 - 访问 http://localhost:9091/user/name ,查看页面返回的属性值
- 修改 Git仓库
user-service
微服务的配置文件user-dev.yml
主要修改test.name
属性的值 (值可以随意,自要展示效果即可) - POST请求:http://localhost:14000/actuator/bus-refresh (配置中心的端口 14000)触发消息总线进行刷新配置
- 重新访问 http://localhost:9091/user/name (返回更改后的值表示成功)