Spring Cloud 学习记录
Spring Cloud Bus
概述
Spring Cloud Bus 将分布式系统的节点与一个轻量级的 message broker 联系起来。然后,这个 broker 可以用来广播状态变化(如配置变化)或其他管理指令。一个关键的想法是,总线(bus)就像 Spring Boot 应用的一个分布式执行器,是可以扩展的。然而,它也可以被用作应用程序之间的通信 channel。这个项目提供了 AMQP broker 或 Kafka 作为传输的 starter。
使用
添加依赖:
添加spring-cloud-starter-bus-amqp或spring-cloud-starter-bus-kafka依赖,Spirng Cloud 会自动处理接来下的事。当在本地主机上运行时,你不需要做任何事情。如果你远程运行,请使用 Spring Cloud 连接器(Connector)或 Spring Boot 约定来定义 broker 凭证,如下面 Rabbit 的例子中所示。
在 application.yml 配置:
1 | spring: |
总线目前支持向所有监听的节点或某一特定服务的所有节点发送消息(由 Eureka 定义)。/bus/* actuator 命名空间有一些 HTTP 端点。目前,有两个已经实现。第一个,/bus/env,发送 key/value 对以更新每个节点的 Spring Environment。第二个,/bus/refresh,重新加载每个应用程序的 configuration,就像它们都被 ping 到了它们的 /refresh 端点。
常用概念
Bus 端点(Endpoint)
Spring Cloud Bus 提供了两个端点
/actuator/busrefresh:对应/actuator/refresh/actuator/busenv:对应/actuator/env
Bus Refresh 端点:清除 RefreshScope 缓存并重新绑定 @ConfigurationProperties
配置:management.endpoints.web.exposure.include=busrefresh
Bus Env 端点:用指定的 key/value 对在多个实例中更新每个实例 environment。
配置:management.endpoints.web.exposure.include=busenv
实例:
应用程序的每个实例都有一个服务 ID,其值可以用 spring.cloud.bus.id 设置,其值应是一个用冒号分隔的标识符列表
ID 的默认值以 app:index:id 的形式构建
1 | app 是 vcap.application.name(如果存在的话),或者是 spring.application.name。 |
HTTP 端点接受一个 “destination” 路径参数,如 /busrefresh/customers:9000,其中 destination 是一个服务 ID。如果该 ID 为总线上的一个实例所拥有,它就会处理该消息,而其他所有实例都会忽略它。