消息总线 —— SpringCloud Bus

打印 上一主题 下一主题

主题 938|帖子 938|积分 2818

Bus 简介

Spring Cloud Bus 是 Spring Cloud 体系内的消息总线,支持 RabbitMQ 和 Kafka 两种消息中间件。所谓消息总线,简单理解就是一个消息中心,众多微服务实例都可以连接到总线上,实例可以往消息中心发送或接收信息,例如:实例 A 发送一条消息到总线上,总线上的实例 B 可以接收到信息(实例 B 订阅了实例 A),消息总线充当一个中间者的角色,使得实例 A 和实例 B 解耦

Spring Cloud Bus 实战

Spring Cloud Bus 可以将 Spring 事件机制和 Stream 结合在一起,具体机制如下:

  • 在需要发布或者监听事件的应用中增加 @RemoteApplicationEventScan 注解,通过该注解
    可以启动 Stream 中消息通道的绑定
  • 对于事件发布,需要承 ApplicationEvent 的扩展类 RemoteApplicationEvent,通过 ApplicationContext.publishEvent() 发布事件时,Spring Cloud Bus 会对所要发布的事件进行包装,形成消息,通过默认的 Spring Cloud Bus 消息通道发送到消息中间件
  • 对于事件监听者,则不需要进行任何变更,仍旧按照 Spring 的方式实现消息的监听i
安装并启动 ZooKeeper 和 Kafka,创建事件发布者项目,引入依赖
  1. <dependency>
  2.     <groupId>org.springframework.cloud</groupId>
  3.     <artifactId>spring-cloud-starter-bus-kafka</artifactId>
  4. </dependency>
复制代码
定义用户事件类 UserEvent,实现 RemoteApplicationEvent
  1. @Data
  2. @Slf4j
  3. @EqualsAndHashCode(callSuper = true)
  4. public class UserEvent extends RemoteApplicationEvent {
  5.     public UserEvent(Object source, String originService, String destination) {
  6.         super(source, originService, destination);
  7.     }
  8. }
复制代码

  • originService:对于事件发布者来说 originService 就是自己
  • destinationService:将事件发布到哪些微服务实例,配置的格式为 {serviceld):{appContextId),在配置时 serviceld 和 appContextld 可以使用通配符,比如 userservice:** 会将事件发布给 userservice 微服务
发布消息代码如下
  1. @Slf4j
  2. @RestController
  3. public class TestCon {
  4.     @Autowired
  5.     private ApplicationContextHolder holder;
  6.     @GetMapping("/test/userEvent")
  7.     public void userAdd() {
  8.         User user = new User();
  9.         user.setId("2");
  10.         user.setName("tom");
  11.         user.setAge(50);
  12.         ApplicationContext ctx = ApplicationContextHolder.getApplicationContext();
  13.         UserEvent event = new UserEvent(user, ctx.getId(), "*:**");
  14.         ctx.publishEvent(event);
  15.     }
  16. }
复制代码
在配置文件中添加如下配置:
  1. spring:
  2.   cloud:
  3.     stream:
  4.       default-binder: kafka
  5.       kafka:
  6.         binder:
  7.           brokers: localhost:9092
复制代码
在启动类添加 @RemoteApplicationEventScan 注解
  1. @SpringBootApplication
  2. @RemoteApplicationEventScan
  3. public class Server01Application {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(Server01Application.class, args);
  6.     }
  7. }
复制代码
创建事件接收者项目,引入和事件发布者同样的依赖,将 UserEvent 类复制到该模块下,实现事件监听类UserEventListener
  1. @Slf4j
  2. @Component
  3. public class UserEventListener implements ApplicationListener<UserEvent> {
  4.     @Override
  5.     public void onApplicationEvent(UserEvent event) {
  6.         log.info("收到用户事件: {}", event);
  7.     }
  8. }
复制代码
加上事件发布者同样的配置和启动类注解
启动两个项目,请求事件发布者的 /test/userEvent 接口,即可发布和接收事件

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王國慶

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表