微服务架构spring cloud - 消息总线Bus

微服务架构spring cloud - 消息总线Bus

1.什么是消息总线

由于配置信息的变更或者其他的一些管理操作,所以需要消息总线。消息总线的意思是使用轻量级的消息代理来构建一个共用的的消息主题让系统中所有的微服务实例都连接上来,该主题中产生的消息会被所有实例监听和消费。

2.消息代理

消息代理是一种消息验证、传输、路由的架构模式。它是一个中间件产品,它的核心是一个消息的路由程序,用来实现接受和分发消息,并根据设定好的消息处理流来转发给正确的应用。

使用场景

  • 将消息路由到一个或多个目的
  • 消息转化为其他的表现方式
  • 执行消息的聚集、消息的分解,并将结果发送到他们的目的地,然后重新组合响应返回给消息用户。
  • 调用Web服务来检索数据
  • 响应事件或错误
  • 使用发布-订阅模式来提供内容或基于主体的消息路由

3.RabbitMQ实现消息总线

rabbitmq是实现了AMQP协议的开源消息代理软件,也称为面向消息的中间件。

基本概念

  1. Broker:可以理解为消息队列服务器的实体,它是一个中间间应用,负责接收消息生产者的消息,然后将消息发送至消息接受者或者其他的Borker.
  2. Exchange:消息交换机,是消息第一个到达的地方,消息通过它指定的路由规则,分发到不同的消息队列中去。
  3. Queue:消息队列,消息通过发送和路由之后最终到达的地方,到达Queue的消息即进入逻辑上等待消费的状态。每个消息通过发送到一个或多个队列
  4. Binding:绑定,它的作用就是把Exchange和Queue按照路由规则绑定起来,也就是Exchange和Queue之间的虚拟连接
  5. Routing key:路由关键字,Exchange根据这个关键字进行消息投递
  6. Virtual host:虚拟主机,它是对Broker的虚拟划分,将消费者、生产者和他们依赖的AMQP相关结构进行隔离,一般都是为了安全考虑。比如,我们可以在一个Broker中设置多个虚拟主机,对不同用户进行权限的分离
  7. Connection:连接,代表生产者、消费者、broker之间进行通信的物理网络
  8. Channel:消息通道,用于连接生产者、消费者的逻辑结构。在客户端的每个连接里,可建立多个Channel,每个Channel代表一个会话任务,通过Channel可以隔离同一连接中的不同交互内容。
  9. Producer:消息生产者,制造消息并发送消息的程序
  10. Consumer:消息消费者,接受消息并处理消息的程序

消息投递到队列的整个过程

客户端连接到消息队列服务器,打开一个Channel

客户端声明一个Exchange,并设置相关属性

客户端声明一个Queue,并设置相关属性

客户端使用Routing Key,在Exchange和Queue之间建立好绑定关系

客户端投递消息到Exchange

Exchange接受到消息后,根据消息的Key和已经设置的Binding,进行消息路由,将消息投递到一个或多个Queue里。

Exchange类型

  1. Direct交换机:完全根据Key进行投递。比如,绑定时设置了Routing Key为abc,那么客户端提交的信息,只有设置了Key为abc的才会被投递到队列。
  2. Topic交换机:对Key进行模式匹配后进行投递,可以使用符号#匹配一个或多个词,符号*匹配正好一个词。比如,abc.#匹配abc.def.gfi ; abc.* 只匹配abc.def
  3. Fanout交换机:不需要任何Key,它采取广播模式,一个消息进来时,投递到与该交换机绑定的所有队列。

消息队列持久化

将数据写入磁盘(durable持久化)

  1. Exchange持久化,在声明时指定durable=>1
  2. Queue持久化,在声明时指定durable=>1
  3. 消息持久化,在投递时指定delivery_mode=>2 (1是非持久化)

如果Exchange和Queue是持久化的,那么Binding也是持久化的。如果有其中一个是非持久化,那么不允许绑定。

快速入门

1.首先确保开启了RabbitMQ服务端

2.新建一个服务实例,配置依赖


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-amqp </artifactId>
  4. </dependency>

3.配置文件

包括rabbitmq的地址以及账号密码


 
 
  1. spring.application. name=rabbitmq-hello
  2. spring.rabbitmq.host=localhost
  3. spring.rabbitmq.port= 5672
  4. spring.rabbitmq.username=guest
  5. spring.rabbitmq.password=guest

4.创建消息生产者

主要是注入一个AmqpTemplate对象进行操作


 
 
  1. @Component
  2. public class Sender {
  3. @Autowired
  4. private AmqpTemplate amqpTemplate;
  5. public void send(){
  6. String context= "hello - llg- "+ new Date();
  7. System.out.println(context);
  8. amqpTemplate.convertAndSend( "hello",context);
  9. }
  10. }

5.创建消息消费者

主要是注入监听的消息队列名


 
 
  1. @Component
  2. @RabbitListener(queues = "hello")
  3. public class Receiver {
  4. @RabbitHandler
  5. public void process(String hello){
  6. System.out.println( "Receiver:"+hello);
  7. }
  8. }

6.在配置文件上配置队列


 
 
  1. @Configuration
  2. public class RabbitConfig {
  3. @Bean
  4. public Queue helloQueue(){
  5. return new Queue( "hello");
  6. }
  7. }

总结:生产和消费是一个异步操作,这也是在分布式系统中要使用消息代理的原因,以此我们可以使用通信来解耦业务逻辑。

当消息发送之后,如果消费者没有消费,那么消息将会在Queue等候,直到消费者上线消费。

整合Spring Cloud Bus

利用消息代理将消息路由到一个或多个目的地实现动态刷新配置

大致过程:通过Eureka进行服务注册后,加入bus配置文件,通过端点/bus/refresh可以不仅刷新本实例的配置信息,还可以通过消息总线通知此服务的所有其他实例。这比端点/refresh的功能是不再仅仅刷新一个实例。

首先添加依赖


 
 
  1. <dependency>
  2. <groupId>org.springframework.boot </groupId>
  3. <artifactId>spring-boot-starter-amqp </artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud </groupId>
  7. <artifactId>spring-cloud-starter-eureka </artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.cloud </groupId>
  11. <artifactId>spring-cloud-bus </artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.cloud </groupId>
  15. <artifactId>spring-cloud-stream-binder-rabbit </artifactId>
  16. </dependency>

然后添加配置信息


 
 
  1. spring.cloud.config.fail-fast= true
  2. spring.application.name=llg
  3. server.port= 7003
  4. eureka.client.service-url.defaultZone=http: //localhost:1111/eureka/
  5. spring.cloud.config.profile=dev
  6. spring.cloud.config.label=master
  7. spring.cloud.config.uri=http: //localhost:7001/
  8. #spring.cloud.config.username=llg
  9. #spring.cloud.config.password=1997729
  10. management.security.enabled= false
  11. spring.rabbitmq.host=localhost
  12. spring.rabbitmq.port= 5672
  13. spring.rabbitmq.username=guest
  14. spring.rabbitmq.password=guest

最后通过访问/bus/refresh 通知所有服务实例

指定刷新范围

通过一个destination参数指定刷新范围

  • /bus/refresh?destination=customers:9000 指定某一个实例
  • /bus/refresh?destination=customers:** 指定某一个服务

架构优化(重点)

经过上述配置发现,如果对某一个实例进行Web Hook的话虽然可以对整个服务的所有实例进行刷新,但是这影响了每个实例的对等性。所以最后的法子是将这个请求/bus/refresh发送到config-server上面,这样子就不会影响了实例的对等性。在这里由于不再是请求发送到某个服务,所以需要使用destination指定某个服务。

RabbitMQ配置

配置详解

  • spring.rabbitmq.address MQ地址,有多个的时候使用逗号分隔开来,由IP和Port组成
  • spring.rabbitmq.cache.channel.checkout-timeout 当缓存已满时,获取Channel的等待时间,单位为毫秒
  • spring.rabbitmq.cache.channel.size 缓存中保持的Channel数量
  • spring.rabbitmq.cache.connection.mode=CHANNEL 连接缓存的模式
  • spring.rabbitmq.cache.connection.size 缓存的连接数
  • spring.rabbitmq.connection-timeout 连接超时参数,单位为毫秒;设置为“0”代表无穷大
  • spring.rabbitmq.dynamic=true 默认创建一个AmqpAdmin的Bean 
  • spring.rabbitmq.host=localohost  Rabbitmq的主机地址
  • spring.rabbitmq.listener.acknowledge-mode 容器的acknowledge模式
  • spring.rabbitmq.listener.auto-startup=true 启动时自动启动容器
  • spring.rabbitmq.listener.concurrency 消费者的最小数量
  • spring.rabbitmq.listener.default-requeue-rejected=true 投递失败时是否重新排队
  • spring.rabbitmq.listener.max-concurrency 消费者的最大数量
  • spring.rabbitmq.listener.prefetch 在单个请求处理中处理的消息个数,它应该大于等于事务数量
  • spring.rabbitmq.listener.retry.enabled=false 不论是不是重试的发布
  • spring.rabbitmq.listener.retry.initial-interval=1000 第一次与第二次投递尝试的时间间隔
  • spring.rabbitmq.listener.retry.max-attempts=3 尝试投递消息的最大数量
  • spring.rabbitmq.listener.retry.max-interval=10000 两次尝试的最大时间间隔
  • spring.rabbitmq.listener.retry.multiplier=1.0 上一次尝试时间间隔的乘数
  • spring.rabbitmq.listener.retry.stateless=true 不论重试是有状态的还是无状态的
  • spring.rabbitmq.listener.transaction-size 在上一个事务中处理的消息数量。为了获得最佳效果,该值应设置为小于等于每个请求中处理的消息个数,即spring.rabbitmq.listener.listener.prefetch 的值
  • spring.rabbitmq.password MQ密码
  • spring.rabbitmq.port MQ端口
  • spring.rabbitmq.publiisher-confirms=false 开启Publisher Confirm 机制
  • spring.rabbitmq.publiisher-returns=false 开启Publisher return 机制
  • spring.rabbitmq.requested-hearted 请求心跳超时时间,单位为秒
  • spring.rabbitmq.ssl.enabled=false 启用SSL支持 
  • spring.rabbitmq.ssl.key-store 保存SSL证书地址
  • spring.rabbitmq.ssl.key-store-password 访问SSL证书地址使用的密码
  • spring.rabbitmq.ssl.trust-store SSL的可信地址
  • spring.rabbitmq.ssl.trust-store-password 访问SSL的可信地址使用的密码
  • spring.rabbitmq.ssl.algorithm SSL算法,默认使用Rabbit的客户端算法库
  • spring.rabbitmq.template.mandatory=false 启用强制消息 
  • spring.rabbitmq.template.receive-timeout=0 receive()的超时时间
  • spring.rabbitmq.template.reply-timeout=5000 sendAndReceive()的超时时间
  • spring.rabbitmq.template.retry.enabled =false 设置为true的时候RabbitTemplate能够实现重试
  • spring.rabbitmq.template.retry.initial-interval=1000  第一次与第二次发布消息的时间间隔
  • spring.rabbitmq.template.retry.max-attempts=3 尝试发布消息的最大数量
  • spring.rabbitmq.template.retry.multiplier 上一次尝试时间间隔的乘数 1.0
  • spring.rabbitmq.username MQ账号
  • spring.rabbitmq.virtual-host 连接到RabbitMQ的虚拟主机

4.Kafaka实现消息总线

5.深入理解-Spring事件

从/bus/refresh发送的请求来看,里面包含某些信息内容

RefreshRemoteApplicationEvent和AckRemoteApplicationEvent共有属性

  • type:消息的时间类型,包含了RefreshRemoteApplicationEvent和AckRemoteApplicationEvent.其中,RefreshRemoteApplication是刷新配置的事件,而AckRemoteApplicationEvent是响应消息已经正确接收的告知消息事件
  • timestamp:消息的时间戳
  • originService:消息的来源服务实例
  • destinationService:消息的目标服务实例 *:** 代表所有实例 
  • id:消息的唯一标识

AckRemoteApplicationEvent私有属性

ackId:对应的消息来源,例如RefreshRemoteApplicationEvent的id

ackDestinationService:Ack消息的目标服务实例 

event:Ack消息的来源事件

事件驱动模型

由于spring-cloud-bus的底层是使用了spring的事件驱动,所以在这里先讲解事件驱动。

spring的时间驱动模型包括了三个基本概念:事件、事件监听者和事件发布者

作用:为Bean与Bean之间通信提供了可能,一个Bean执行完任务后可以通过发布事件使另一个Bean做出相应处理

事件

spring定义了事件的抽象类ApplicationEvent,包括了两个变量,一个是时间戳,而另一个比较特别就是source源事件对象

当我们需要自定义事件的时候只需要继承这个类就可以了,例如RefreshRemoteApplicationEvent和AckRemoteApplicationEvent


 
 
  1. public abstract class ApplicationEvent extends EventObject {
  2. private static final long serialVersionUID = 7099057708183571937L;
  3. private final long timestamp = System.currentTimeMillis();
  4. public ApplicationEvent(Object source) {
  5. super(source);
  6. }
  7. public final long getTimestamp() {
  8. return this.timestamp;
  9. }
  10. }

事件监听者

spring定义了ApplicationListener接口,针对某个ApplicationEvent子类的监听和处理者


 
 
  1. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  2. void onApplicationEvent(E var1);
  3. }

事件发布者

spring中定义了ApplicationEventPublisher和ApplicationEventMulticaster两个接口用来发布事件

ApplicationEventPublisher:定义了发布事件的函数

ApplicationEventMulticaster:定义了对ApplicationListener的维护操作(比如新增、移除等)以及将ApplicationEvent广播给可用ApplicationListener的操作


 
 
  1. public interface ApplicationEventPublisher {
  2. void publishEvent(ApplicationEvent var1);
  3. void publishEvent(Object var1);
  4. }

 
 
  1. public interface ApplicationEventMulticaster {
  2. void addApplicationListener(ApplicationListener<?> var1);
  3. void addApplicationListenerBean(String var1);
  4. void removeApplicationListener(ApplicationListener<?> var1);
  5. void removeApplicationListenerBean(String var1);
  6. void removeAllListeners();
  7. void multicastEvent(ApplicationEvent var1);
  8. void multicastEvent(ApplicationEvent var1, ResolvableType var2);
  9. }

ApplicationEventPublish的实现类AbstractApplicationContext实现了publishEvent的函数,而这个函数里面可以发现最终会调用ApplicationEventMulticase的multicastEvent来具体实现发布事件给监听者的操作


 
 
  1. protected void publishEvent(Object event, ResolvableType eventType) {
  2. Assert.notNull( event, "Event must not be null");
  3. if ( this.logger.isTraceEnabled()) {
  4. this.logger.trace( "Publishing event in " + this.getDisplayName() + ": " + event);
  5. }
  6. Object applicationEvent;
  7. if ( event instanceof ApplicationEvent) {
  8. applicationEvent = (ApplicationEvent) event;
  9. } else {
  10. applicationEvent = new PayloadApplicationEvent( this, event);
  11. if (eventType == null) {
  12. eventType = ((PayloadApplicationEvent)applicationEvent).getResolvableType();
  13. }
  14. }
  15. if ( this.earlyApplicationEvents != null) {
  16. this.earlyApplicationEvents. add(applicationEvent);
  17. } else {
  18. this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType);
  19. }
  20. if ( this.parent != null) {
  21. if ( this.parent instanceof AbstractApplicationContext) {
  22. ((AbstractApplicationContext) this.parent).publishEvent( event, eventType);
  23. } else {
  24. this.parent.publishEvent( event);
  25. }
  26. }
  27. }

所以接着我们去看ApplicationEventMulticaster的实现类SimpleApplicationEventMulticaster中,具体如下:

从代码中可以看到,通过遍历ApplicationListener集合,找到特定事件的监听器,然后调用监听器的onApplicationEvent的函数来做出对具体时间的处理(onApplicationEvent相当于onclick)


 
 
  1. public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
  2. ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType( event);
  3. Iterator var4 = this.getApplicationListeners( event, type).iterator();
  4. while(var4.hasNext()) {
  5. final ApplicationListener<?> listener = (ApplicationListener)var4.next();
  6. Executor executor = this.getTaskExecutor();
  7. if (executor != null) {
  8. executor.execute( new Runnable() {
  9. public void run() {
  10. SimpleApplicationEventMulticaster. this.invokeListener(listener, event);
  11. }
  12. });
  13. } else {
  14. this.invokeListener(listener, event);
  15. }
  16. }
  17. }

 
 
  1. protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
  2. ErrorHandler errorHandler = this.getErrorHandler();
  3. if (errorHandler != null) {
  4. try {
  5. this.doInvokeListener(listener, event);
  6. } catch (Throwable var5) {
  7. errorHandler.handleError(var5);
  8. }
  9. } else {
  10. this.doInvokeListener(listener, event);
  11. }
  12. }
  13. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  14. try {
  15. listener.onApplicationEvent( event);
  16. } catch (ClassCastException var6) {
  17. String msg = var6.getMessage();
  18. if (msg != null && ! this.matchesClassCastMessage(msg, event.getClass().getName())) {
  19. throw var6;
  20. }
  21. Log logger = LogFactory.getLog( this.getClass());
  22. if (logger.isDebugEnabled()) {
  23. logger.debug( "Non-matching event type for listener: " + listener, var6);
  24. }
  25. }
  26. }

实战演练

首先定义事件


 
 
  1. public class LLGEvent extends ApplicationEvent {
  2. private String username;
  3. private String password;
  4. public LLGEvent(Object source, String username, String password) {
  5. super(source);
  6. this.username = username;
  7. this.password = password;
  8. }
  9. }

接着配置监听器


 
 
  1. @Component
  2. public class LLGListener implements ApplicationListener<LLGEvent> {
  3. @Override
  4. public void onApplicationEvent(LLGEvent llgEvent) {
  5. int i= 23;
  6. System.out.println(llgEvent.getPassword()+llgEvent.getPassword());
  7. }
  8. }

最后使用ApplicationContext发布事件,它实现了publishEvent方法


 
 
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class ConfigClientApplicationTests {
  4. @Autowired
  5. ApplicationContext applicationContext;
  6. @Test
  7. public void contextLoads() {
  8. applicationContext.publishEvent( new LLGEvent( this, "llg", "123456"));
  9. }
  10. }

 

6.深入理解spring-cloud-bus

事件定义

首先查看RemoteApplicationEvent

从头部注解可以看出jackson对多态类型的处理注解,当进行序列化时,会使用子类的名称作为type属性的值,比如之前示例中的“type”:"RefreshRemoteApplication"


 
 
  1. @JsonTypeInfo(
  2. use = Id.NAME,
  3. property = "type"
  4. )
  5. @JsonIgnoreProperties({"source"})

 
 
  1. public abstract class RemoteApplicationEvent extends ApplicationEvent {
  2. private static final Object TRANSIENT_SOURCE = new Object();
  3. private final String originService;
  4. private final String destinationService;
  5. private final String id;

接着看其他子类

RefreshRemoteApplicationEvent

从源代码可以看出,子类没有重写或者增加任何方法


 
 
  1. public class RefreshRemoteApplicationEvent extends RemoteApplicationEvent {
  2. private RefreshRemoteApplicationEvent() {
  3. }
  4. public RefreshRemoteApplicationEvent(Object source, String originService, String destinationService) {
  5. super(source, originService, destinationService);
  6. }
  7. }

AckRemoteApplicationEvent

该事件用于告知某个事件消息已经被接受,通过该事件消息可以监控各个事件消息的响应


 
 
  1. public class AckRemoteApplicationEvent extends RemoteApplicationEvent {
  2. private final String ackId;
  3. private final String ackDestinationService;
  4. private Class<? extends RemoteApplicationEvent> event;
  5. private AckRemoteApplicationEvent() {
  6. this.ackDestinationService = null;
  7. this.ackId = null;
  8. this.event = null;
  9. }
  10. public AckRemoteApplicationEvent(Object source, String originService, String destinationService, String ackDestinationService, String ackId, Class<? extends RemoteApplicationEvent> type) {
  11. super(source, originService, destinationService);
  12. this.ackDestinationService = ackDestinationService;
  13. this.ackId = ackId;
  14. this.event = type;
  15. }
  16. public String getAckId() {
  17. return this.ackId;
  18. }
  19. public String getAckDestinationService() {
  20. return this.ackDestinationService;
  21. }
  22. public Class<? extends RemoteApplicationEvent> getEvent() {
  23. return this.event;
  24. }
  25. @JsonProperty("event")
  26. public void setEventName(String eventName) {
  27. try {
  28. this.event = Class.forName(eventName);
  29. } catch (ClassNotFoundException var3) {
  30. this.event = UnknownRemoteApplicationEvent. class;
  31. }
  32. }

EnvironmentChangeRemoteApplicationEvent

用于更新消息总线上每个节点的Spring环境属性。接受消息的节点就是根据该Map对象中的属性来覆盖本地的Spring环境属性


 
 
  1. public class EnvironmentChangeRemoteApplicationEvent extends RemoteApplicationEvent {
  2. private final Map< String, String> values;
  3. private EnvironmentChangeRemoteApplicationEvent() {
  4. this.values = null;
  5. }
  6. public EnvironmentChangeRemoteApplicationEvent( Object source, String originService, String destinationService, Map< String, String> values) {
  7. super(source, originService, destinationService);
  8. this.values = values;
  9. }
  10. public Map< String, String> getValues() {
  11. return this.values;
  12. }

SentApplicationEvent

主要用于发送信号来表示一个远程事件已经在系统中发送到某些地方了,它本身不是一个远程的事件,不会被发送到消息总线上


 
 
  1. @JsonTypeInfo(
  2. use = Id.NAME,
  3. property = "type"
  4. )
  5. @JsonIgnoreProperties({"source"})
  6. public class SentApplicationEvent extends ApplicationEvent {
  7. private static final Object TRANSIENT_SOURCE = new Object();
  8. private final String originService;
  9. private final String destinationService;
  10. private final String id;
  11. private Class<? extends RemoteApplicationEvent> type;
  12. protected SentApplicationEvent() {
  13. this(TRANSIENT_SOURCE, (String) null, (String) null, (String) null, RemoteApplicationEvent. class);
  14. }
  15. public SentApplicationEvent(Object source, String originService, String destinationService, String id, Class<? extends RemoteApplicationEvent> type) {
  16. super(source);
  17. this.originService = originService;
  18. this.type = type;
  19. if (destinationService == null) {
  20. destinationService = "*";
  21. }
  22. if (!destinationService.contains( ":")) {
  23. destinationService = destinationService + ":**";
  24. }
  25. this.destinationService = destinationService;
  26. this.id = id;
  27. }

事件监听器

RefreshListener和EnvironmentChangeListener都继承了Spring事件模型中的监听器接口ApplicationListener.

RefreshListener

从泛型中我们可以看到该监听器就是针对我们之前所介绍的RefreshRemoteApplicationEvent事件的,其中onApplicationEvent函数中调用了ContextRefresher 中 refresh()函数进行配置属性的刷新,从refresh可以看到还发布了一个EnvironmentChangeEvent事件.refresh俩面还有个change方法,里面有加载新的配置,通过加载远程git配置文件获得.并且方法是使用了RestTmeplate进行请求获取。


 
 
  1. public class RefreshListener implements ApplicationListener<RefreshRemoteApplicationEvent> {
  2. private static Log log = LogFactory.getLog(RefreshListener.class);
  3. private ContextRefresher contextRefresher;
  4. public RefreshListener(ContextRefresher contextRefresher) {
  5. this.contextRefresher = contextRefresher;
  6. }
  7. public void onApplicationEvent(RefreshRemoteApplicationEvent event) {
  8. Set<String> keys = this.contextRefresher.refresh();
  9. log.info( "Received remote refresh request. Keys refreshed " + keys);
  10. }
  11. }

 
 
  1. public synchronized Set<String> refresh() {
  2. Map<String, Object> before = this.extract( this.context.getEnvironment().getPropertySources());
  3. this.addConfigFilesToEnvironment();
  4. Set<String> keys = this.changes(before, this.extract( this.context.getEnvironment().getPropertySources())).keySet();
  5. this.context.publishEvent(new EnvironmentChangeEvent( this.context, keys));
  6. this.scope.refreshAll();
  7. return keys;
  8. }

所以我们接着去看EnvironmentChangeListener监听器

获取了之前提到的事件中定义的Map对象,然后通过遍历来更新EnvironmentManager中的属性内容


 
 
  1. public class EnvironmentChangeListener implements ApplicationListener<EnvironmentChangeRemoteApplicationEvent> {
  2. private static Log log = LogFactory.getLog(EnvironmentChangeListener. class);
  3. @Autowired
  4. private EnvironmentManager env;
  5. public EnvironmentChangeListener() {
  6. }
  7. public void onApplicationEvent(EnvironmentChangeRemoteApplicationEvent event) {
  8. Map< String, String> values = event.getValues();
  9. log.info( "Received remote environment change request. Keys/values to update " + values);
  10. Iterator var3 = values.entrySet().iterator();
  11. while(var3.hasNext()) {
  12. Entry< String, String> entry = (Entry)var3. next();
  13. this.env.setProperty(( String)entry.getKey(), ( String)entry.getValue());
  14. }
  15. }
  16. }

事件跟踪

TraceListener

从代码中可以看到@EventLiisterner注解,自动注册为一个监听器bean.通过trace端点可以跟踪最近的100条数据,关于发送和接受到的Ack事件信息,信息存储在内存中。

spring.cloud.bus.trace.enabled=true 开启trace端点

 


 
 
  1. public class TraceListener {
  2. private static Log log = LogFactory.getLog(TraceListener.class);
  3. private TraceRepository repository;
  4. public TraceListener(TraceRepository repository) {
  5. this.repository = repository;
  6. }
  7. @ EventListener
  8. public void onAck (AckRemoteApplicationEvent event) {
  9. this.repository.add( this.getReceivedTrace(event));
  10. }
  11. @ EventListener
  12. public void onSend (SentApplicationEvent event) {
  13. this.repository.add( this.getSentTrace(event));
  14. }
  15. protected Map<String, Object> getSentTrace(SentApplicationEvent event) {
  16. Map<String, Object> map = new LinkedHashMap();
  17. map.put( "signal", "spring.cloud.bus.sent");
  18. map.put( "type", event.getType().getSimpleName());
  19. map.put( "id", event.getId());
  20. map.put( "origin", event.getOriginService());
  21. map.put( "destination", event.getDestinationService());
  22. if ( log.isDebugEnabled()) {
  23. log.debug( map);
  24. }
  25. return map;
  26. }
  27. protected Map<String, Object> getReceivedTrace(AckRemoteApplicationEvent event) {
  28. Map<String, Object> map = new LinkedHashMap();
  29. map.put( "signal", "spring.cloud.bus.ack");
  30. map.put( "event", event.getEvent().getSimpleName());
  31. map.put( "id", event.getAckId());
  32. map.put( "origin", event.getOriginService());
  33. map.put( "destination", event.getAckDestinationService());
  34. if ( log.isDebugEnabled()) {
  35. log.debug( map);
  36. }
  37. return map;
  38. }
  39. }

事件发布

首先查看spring cloud bus 启动时加载的一些基础类和接口,包括自动化配置类BusAutoConfiguration 、属性定义类BusProperties等

该接口定义了发送消息的抽象接口


 
 
  1. @Autowired
  2. @Output("springCloudBusOutput")
  3. private MessageChannel cloudBusOutboundChannel;

通过ServiceMatcher的函数方法,判断事件来源是否是自己,以及判断目标是否是自己,以此作为依据是否要响应信息来进行事件的处理


 
 
  1. @Autowired
  2. private ServiceMatcher serviceMatcher;

 
 
  1. public boolean isFromSelf(RemoteApplicationEvent event) {
  2. String originService = event.getOriginService();
  3. String serviceId = this.getServiceId();
  4. return this.matcher.match(originService, serviceId);
  5. }
  6. public boolean isForSelf(RemoteApplicationEvent event) {
  7. String destinationService = event.getDestinationService();
  8. return destinationService == null || destinationService.trim().isEmpty() || this.matcher.match(destinationService, this.getServiceId());
  9. }

定义了消息服务的绑定属性 


 
 
  1. @Autowired
  2. private BindingServiceProperties bindings;

定义了Spring Cloud Bus 的属性 


 
 
  1. @Autowired
  2. private BusProperties bus;

 spring.cloud.bus为配置文件前缀。destination和enabled属性分别定义了默认的队列(Queue)或主题(Topic)是否连接到消息总线,所以我们通过spring.cloud.bus.destination来修改消息总线使用的队列或主题名称,以及使用spring.cloud.bus.enabled属性来设置应用是否要连接到消息总线上


 
 
  1. @ConfigurationProperties( "spring.cloud.bus")
  2. public class BusProperties {
  3. private BusProperties.Env env = new BusProperties.Env();
  4. private BusProperties.Refresh refresh = new BusProperties.Refresh();
  5. private BusProperties.Ack ack = new BusProperties.Ack();
  6. private BusProperties.Trace trace = new BusProperties.Trace();
  7. private String destination = "springCloudBus";
  8. private boolean enabled = true;

 监听本地事件来进行消息的发送,可以看到有个send的方法,把事件发送了出去


 
 
  1. @EventListener(
  2. classes = {RemoteApplicationEvent.class}
  3. )
  4. public void acceptLocal(RemoteApplicationEvent event) {
  5. if ( this.serviceMatcher.isFromSelf( event) && !( event instanceof AckRemoteApplicationEvent)) {
  6. this.cloudBusOutboundChannel.send(MessageBuilder.withPayload( event).build());
  7. }
  8. }

根据acceptRemote方法来监听消息代理的输入通道,并根据事件类型和配置内容来确定是否要发布事件给我们之前分析的几个事件监听器来做对事件做具体的处理

根据acceptLocal方法用来监听本地的事件,针对事件来源是自己,并且事件类型不是AckRemoteApplicationEvent的内容通过消息代理的输出通道发送到总线上去。 

主要acceptRemote就是从消息代理那里拿到事件,然后决定是否发布事件到监听器


 
 
  1. @StreamListener("springCloudBusInput")
  2. public void acceptRemote(RemoteApplicationEvent event) {
  3. if (event instanceof AckRemoteApplicationEvent) {
  4. if ( this.bus.getTrace().isEnabled() && ! this.serviceMatcher.isFromSelf(event) && this.applicationEventPublisher != null) {
  5. this.applicationEventPublisher.publishEvent(event);
  6. }
  7. } else {
  8. if ( this.serviceMatcher.isForSelf(event) && this.applicationEventPublisher != null) {
  9. if (! this.serviceMatcher.isFromSelf(event)) {
  10. this.applicationEventPublisher.publishEvent(event);
  11. }
  12. if ( this.bus.getAck().isEnabled()) {
  13. AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent( this, this.serviceMatcher.getServiceId(), this.bus.getAck().getDestinationService(), event.getDestinationService(), event.getId(), event.getClass());
  14. this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(ack).build());
  15. this.applicationEventPublisher.publishEvent(ack);
  16. }
  17. }
  18. if ( this.bus.getTrace().isEnabled() && this.applicationEventPublisher != null) {
  19. this.applicationEventPublisher.publishEvent(new SentApplicationEvent( this, event.getOriginService(), event.getDestinationService(), event.getId(), event.getClass()));
  20. }
  21. }
  22. }

控制端点

发送到消息总线上用来触发各个节点的事件处理的动作

主要是由/bus/refresh和/bus/env实现,由于端点是由顶级基类Endpoint继承而来,所以我们一步步查看

Endpoint

接口中定义了监控端点需要暴露的一些有用信息,比如id、是否开启标志、是否开启敏感信息标识等


 
 
  1. public interface Endpoint<T> {
  2. String getId();
  3. boolean isEnabled();
  4. boolean isSensitive();
  5. T invoke();
  6. }

AbstractEndpoint

抽象类是对Endpoint的基础实现,在该类抽象类中引入了Environment接口对象,从而对接口中暴露信息的控制可以通过配置文件的方式来控制


 
 
  1. public abstract class AbstractEndpoint<T> implements Endpoint<T>, EnvironmentAware {
  2. private static final Pattern ID_PATTERN = Pattern.compile( "\\w+");
  3. private Environment environment;
  4. private String id;
  5. private final boolean sensitiveDefault;
  6. private Boolean sensitive;
  7. private Boolean enabled;

MvcEndPoint

接口,定义了Endpoint在MVC层的策略。在这里可以通过使用SpringMVC的@RequestMapping注解来定义端点暴露的接口地址


 
 
  1. public interface MvcEndpoint {
  2. ResponseEntity<Map<String, String>> DISABLED_RESPONSE = new ResponseEntity(Collections.singletonMap( "message", "This endpoint is disabled"), HttpStatus.NOT_FOUND);
  3. String getPath();
  4. boolean isSensitive();
  5. Class<? extends Endpoint> getEndpointType();
  6. }

BusEndpoint

继承自AbstractEndpoint,默认id为bus,端点默认敏感标识为true


 
 
  1. @ConfigurationProperties(
  2. prefix = "endpoints.bus",
  3. ignoreUnknownFields = false
  4. )
  5. public class BusEndpoint extends AbstractEndpoint<Collection<String>> {
  6. public BusEndpoint() {
  7. super( "bus");
  8. }
  9. public Collection<String> invoke() {
  10. return Collections.emptyList();
  11. }
  12. }

AbstractEndpoint

实现了mvc接口来暴露MVC层的接口,同时关联了BusEndpoint对象,大部分信息通过BusEndpoint获取信息,例如path


 
 
  1. public class AbstractBusEndpoint implements MvcEndpoint {
  2. private ApplicationEventPublisher context;
  3. private BusEndpoint delegate;
  4. private String appId;
  5. public AbstractBusEndpoint(ApplicationEventPublisher context, String appId, BusEndpoint busEndpoint) {
  6. this.context = context;
  7. this.appId = appId;
  8. this. delegate = busEndpoint;
  9. }
  10. protected String getInstanceId() {
  11. return this.appId;
  12. }
  13. protected void publish(ApplicationEvent event) {
  14. this.context.publishEvent( event);
  15. }
  16. public String getPath() {
  17. return "/" + this. delegate.getId();
  18. }
  19. public boolean isSensitive() {
  20. return this. delegate.isSensitive();
  21. }
  22. public Class<? extends Endpoint> getEndpointType() {
  23. return this. delegate.getClass();
  24. }
  25. }

RefreshBusPoint

由于在父类的getPath是由id组成,所以完整的path为/bus/refresh


 
 
  1. @ManagedResource
  2. public class RefreshBusEndpoint extends AbstractBusEndpoint {
  3. public RefreshBusEndpoint(ApplicationEventPublisher context, String id, BusEndpoint delegate) {
  4. super(context, id, delegate);
  5. }
  6. @RequestMapping(
  7. value = { "refresh"},
  8. method = {RequestMethod.POST}
  9. )
  10. @ResponseBody
  11. @ManagedOperation
  12. public void refresh(@RequestParam(value = "destination",required = false) String destination) {
  13. this.publish( new RefreshRemoteApplicationEvent( this, this.getInstanceId(), destination));
  14. }
  15. }

EnvironmentBusEndpoint

实现与RefreshBusEndpoint类似,提供map参数设定需要更新的配置信息


 
 
  1. @ManagedResource
  2. public class EnvironmentBusEndpoint extends AbstractBusEndpoint {
  3. public EnvironmentBusEndpoint(ApplicationEventPublisher context, String id, BusEndpoint delegate) {
  4. super(context, id, delegate);
  5. }
  6. @RequestMapping(
  7. value = { "env"},
  8. method = {RequestMethod.POST}
  9. )
  10. @ResponseBody
  11. @ManagedOperation
  12. public void env(@RequestParam Map<String, String> params, @RequestParam(value = "destination",required = false) String destination) {
  13. this.publish( new EnvironmentChangeRemoteApplicationEvent( this, this.getInstanceId(), destination, params));
  14. }
  15. }

7.总结

从kafka的控制台可以看到,通过消息中间件的功能来达到发布事件的作用。大致过程就是通过访问一个特定的URL也就是/actuator/bus-refresh的方式,发送了一个特定的消息到消息中间件的T

首先通过post请求访问/bus/refresh ,触发了一个事件通过publish发布了此事件,监听器捕获到这个事件进行rest的配置信息请求,并且bus监听了这些有关的事件,当发布了一个刷新事件,则会发送事件消息到代理服务器,并且代理服务器把消息发送到所有订阅了信息的实例,消息里面包括了事件类型、服务范围等,由destination确定。所有实例因为订阅了topic,所以接受到消息后由于有一个@StreamListener监听了消息代理的数据输入流,接受到事件信息后再发布事件,继续触发刷新rest请求。

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值