当前位置:   article > 正文

Spring Cloud Bus中的事件的订阅与发布(二)

springcloud处理事件发布的方法

在之前的文章Spring Cloud Bus中的事件的订阅与发布(一)介绍了消息总线的相关事件。 本文主要介绍消息总线的事件监听器以及消息的订阅与发布。

事件监听器

Spring Cloud Bus中,事件监听器的定义可以是实现ApplicationListener接口,或者是使用@EventListener注解的形式。我们看一下事件监听器的类图

监听器
ApplicationListener接口实现有两个:刷新监听器 RefreshListener和环境变更监听器 EnvironmentChangeListener

RefreshListener

RefreshListener对应的事件是RefreshRemoteApplicationEvent

  1. public class RefreshListener
  2. implements ApplicationListener<RefreshRemoteApplicationEvent> {
  3. private ContextRefresher contextRefresher;
  4. public RefreshListener(ContextRefresher contextRefresher) {
  5. this.contextRefresher = contextRefresher;
  6. }
  7. @Override
  8. public void onApplicationEvent(RefreshRemoteApplicationEvent event) {
  9. Set<String> keys = contextRefresher.refresh();
  10. log.info("Received remote refresh request. Keys refreshed " + keys);
  11. }
  12. }
  13. 复制代码

对于刷新时间的处理,调用ContextRefresherrefresh()方法,而定义在Spring Cloud Context中的ContextRefresher用于提供上下文刷新的功能。我们具体看一下refresh()方法。

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

实现很简单,先获取之前环境变量的key-value,然后重新加载新的配置环境文件,通过比对新旧环境变量的map集合,然后发布新的环境变更EnvironmentChangeEvent的事件。this.scope.refreshAll()销毁了在这个范围内,当前实例的所有bean并在下次方法的执行时强制刷新。

EnvironmentChangeListener

EnvironmentChangeListener对应的事件类是EnvironmentChangeRemoteApplicationEvent

  1. public class EnvironmentChangeListener
  2. implements ApplicationListener<EnvironmentChangeRemoteApplicationEvent> {
  3. @Autowired
  4. private EnvironmentManager env;
  5. @Override
  6. public void onApplicationEvent(EnvironmentChangeRemoteApplicationEvent event) {
  7. Map<String, String> values = event.getValues();
  8. for (Map.Entry<String, String> entry : values.entrySet()) {
  9. env.setProperty(entry.getKey(), entry.getValue());
  10. }
  11. }
  12. }
  13. 复制代码

RefreshListener的实现中,可以知道该事件的实现最终又发布了一个新的事件EnvironmentChangeListener。在刷新监听器中,构造了变更了的环境变量的map,交给环境变更监听器。上面对环境变更事件的处理,遍历变更了的配置环境属性,并在本地应用程序的环境中将新的属性值设置到对应的键。

TraceListener

TraceListener的实现是通过注解@EventListener的形式,监听的事件为:确认事件AckRemoteApplicationEvent和发送事件SentApplicationEvent

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

在SentTrace中,主要记录了signal、事件类型type、id、源服务origin和目的服务destination的属性值。而在ReceivedTrace中,表示对事件的确认,主要记录了signal、事件类型event、id、源服务origin和目的服务destination的属性值。这些信息默认存储于内存中,可以通过/trace端点获取最近的事件信息,如下图所示:

  1. {
  2. "timestamp": 1517229555629,
  3. "info": {
  4. "signal": "spring.cloud.bus.sent",
  5. "type": "RefreshRemoteApplicationEvent",
  6. "id": "c73a9792-9409-47af-993c-65526edf0070",
  7. "origin": "config-server:8888",
  8. "destination": "config-client:8000:**"
  9. }
  10. },
  11. {
  12. "timestamp": 1517227659384,
  13. "info": {
  14. "signal": "spring.cloud.bus.ack",
  15. "event": "RefreshRemoteApplicationEvent",
  16. "id": "846f3a17-c344-4d29-93f3-01b73c5bf58f",
  17. "origin": "config-client:8000",
  18. "destination": "config-client:8000:**"
  19. }
  20. }
  21. 复制代码

至于事件的发起,我们将在下一节结合消息的订阅与发布一起讲解。

消息的订阅与发布

Spring Cloud Bus基于Spring Cloud Stream,对特定主题的消息进行订阅与发布,事件以消息的形式传递到其他服务实例。

通道定义

既然是基于stream,我们首先看一下input和output的通道定义。

  1. public interface SpringCloudBusClient {
  2. String INPUT = "springCloudBusInput";
  3. String OUTPUT = "springCloudBusOutput";
  4. @Output(SpringCloudBusClient.OUTPUT)
  5. MessageChannel springCloudBusOutput();
  6. @Input(SpringCloudBusClient.INPUT)
  7. SubscribableChannel springCloudBusInput();
  8. }
  9. 复制代码

可以看到,bus中定义了springCloudBusInputspringCloudBusOutput两个通道,分别用于定于订阅与发布springCloudBus的消息。

bus属性定义

其次,我们看一下bus中关于stream的属性定义。在基础应用中我们就知道bus订阅的话题是springCloudBus,下面看一下在bus中的其他属性的定义。

  1. @ConfigurationProperties("spring.cloud.bus")
  2. public class BusProperties {
  3. //环境变更相关的属性
  4. private Env env = new Env();
  5. // 刷新事件相关的属性
  6. private Refresh refresh = new Refresh();
  7. //与ack相关的属性
  8. private Ack ack = new Ack();
  9. //与追踪ack相关的属性
  10. private Trace trace = new Trace();
  11. //Spring Cloud Stream消息的话题
  12. private String destination = "springCloudBus";
  13. //标志位,bus是否可用
  14. private boolean enabled = true;
  15. ...
  16. }
  17. 复制代码

上面的bus属性,设置了一些默认值,正好与事实也是相符的,我们没有进行任何spring.cloud.bus配置也能够进行正常运行。通过在配置文件中修改相应的属性,实现bus的更多功能扩展。env、refresh、ack和trace分别对应不同的事件,在配置文件中有一个开关属性,默认都是开启的,我们可以根据需要进行关闭。

消息的监听与发送

上面两部分讲了stream通道和基本属性的定义,最后我们看下bus中对指定主题的消息如何发送与监听处理。在META-INF/spring.factories配置了EnableAutoConfiguration配置项为BusAutoConfiguration,在服务启动时会自动加载到Spring容器中,其中对于指定主题的消息如何发送与监听处理如下:

  1. @Configuration
  2. @ConditionalOnBusEnabled //bus启用的开关
  3. @EnableBinding(SpringCloudBusClient.class) //绑定通道
  4. @EnableConfigurationProperties(BusProperties.class)
  5. public class BusAutoConfiguration implements ApplicationEventPublisherAware {
  6. //注入source接口,用于发送消息
  7. @Autowired
  8. @Output(SpringCloudBusClient.OUTPUT)
  9. private MessageChannel cloudBusOutboundChannel;
  10. // 监听RemoteApplicationEvent事件
  11. @EventListener(classes = RemoteApplicationEvent.class)
  12. public void acceptLocal(RemoteApplicationEvent event) {
  13. if (this.serviceMatcher.isFromSelf(event)
  14. && !(event instanceof AckRemoteApplicationEvent)) {
  15. //当事件是来自自己的并且不是ack事件,则发送消息
  16. this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(event).build());
  17. }
  18. }
  19. //消息的消费,也是事件的发起
  20. @StreamListener(SpringCloudBusClient.INPUT)
  21. public void acceptRemote(RemoteApplicationEvent event) {
  22. if (event instanceof AckRemoteApplicationEvent) {
  23. //ack事件
  24. if (this.bus.getTrace().isEnabled() && !this.serviceMatcher.isFromSelf(event)
  25. && this.applicationEventPublisher != null) {
  26. //当开启bus追踪且不是自己的ack事件,则通知所有的注册该事件的监听者,否则直接返回
  27. this.applicationEventPublisher.publishEvent(event);
  28. }
  29. return;
  30. }
  31. //消费消息,该消息属于自己
  32. if (this.serviceMatcher.isForSelf(event)
  33. && this.applicationEventPublisher != null) {
  34. //不是自己发布的事件,正常处理
  35. if (!this.serviceMatcher.isFromSelf(event)) {
  36. this.applicationEventPublisher.publishEvent(event);
  37. }
  38. //消费之后,需要发送ack确认事件
  39. if (this.bus.getAck().isEnabled()) {
  40. AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent(this,
  41. this.serviceMatcher.getServiceId(),
  42. this.bus.getAck().getDestinationService(),
  43. event.getDestinationService(), event.getId(), event.getClass());
  44. this.cloudBusOutboundChannel
  45. .send(MessageBuilder.withPayload(ack).build());
  46. this.applicationEventPublisher.publishEvent(ack);
  47. }
  48. }
  49. //事件追踪相关,若是开启追踪事件则执行
  50. if (this.bus.getTrace().isEnabled() && this.applicationEventPublisher != null) {
  51. // 不论其来源,准备发送事件,发布了之后供本地消费
  52. this.applicationEventPublisher.publishEvent(new SentApplicationEvent(this,
  53. event.getOriginService(), event.getDestinationService(),
  54. event.getId(), event.getClass()));
  55. }
  56. }
  57. //...
  58. }
  59. 复制代码

@ConditionalOnBusEnabled注解是bus的开关,默认开启。@EnableBinding绑定了SpringCloudBusClient中定义的通道。在应用服务启动时,自动化配置类加载了bus的API端点、刷新、ACK追踪以及bus环境变量的配置等beans。 @Output表示输出output绑定目标将由框架创建,由该通道发送消息。 还涉及到上面列出来的两个主要方法:acceptLocalacceptRemote

acceptLocal是一个基于注解实现的事件监听器,监听的事件类型是RemoteApplicationEvent,对于该事件的处理方法是,当事件是来自自己的并且不是ack事件,则发送消息。

@StreamListener注解是Spring Cloud Stream中提供的,用来标识一个方法作为@EnableBinding绑定的input通道的监听器。acceptRemote方法, 传递的参数RemoteApplicationEvent就是stream中的消息。如果是确认类事件,当开启了事件追踪且事件不是来自于自身,则发布该事件,对于确认类事件,处理已经完成; 如果自身需要处理该事件且该事件不是来自自身,则发布该事件。需要注意的是,当开启事件追踪时,构造一个确认事件并将该事件发布;最后,当开启了事件追踪,这边的处理是注册已发送的事件,以便发布供本地消费,而不论其来源。

总结

本文在上一篇介绍Spring Cloud Bus中的事件基础上,结合源码继续介绍事件的监听器以及事件的订阅与发布是如何在消息总线中实现的。 消息总线常用于传播状态的变更和管理指令的发布。而消息总线最常用的场景就是更新应用服务的配置信息,需要结合Config Server使用,当然消息总线的实现其实是基于Spring Cloud Stream,Stream封装了各种不同的MQ中间件,产生的消息实则是推送配置信息的变更。

订阅最新文章,欢迎关注我的公众号

参考

Spring Cloud Bus-v1.3.3

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/960532
推荐阅读
相关标签
  

闽ICP备14008679号