spring cloud之Bus回顾

最开始学习Bus时,为了刷新Config配置,后面很少用了,发现这个它的用途很大的,spring cloud不是想进能进的。

server

下面这里其实就是重复了下Config-server流程,略有改动

1、pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、配置添加

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
management:
  security:
    enabled: false
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

client

1、pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

2、配置添加

spring:
  cloud:
    stream:
      default-binder: rabbit # 如果pom同时也引入了kafka,添加这个配置指定消息中间件
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
management:
  security:
    enabled: false
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

访问

然后就可以访问了http://localhost:26000/actuator/bus-refresh,这是刷新所有的服务配置
http://localhost:26000/actuator/bus-refresh/bus-client-1这是刷新指定的服务配置

其他用途

事件对象:Bus中定义的一个事件类,通常是一个Pojo对象,包含了消费者需要的信息
事件发布:Bus作为生产者,将事件对象通过广播的形式发布出去
事件监听:由消费者主动监听Bus的事件发布动作,当获取到事件对象后会调用处理方法进行消费

@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private ApplicationContext applicationContext;
@PostMapping("/bus/publish/myevent")
 public boolean publishMyEvent(@RequestBody EventBody body) {
     MyEvent event = new MyEvent(body, applicationContext.getId(), "");
     try {
         // 可以注入ApplicationEventPublisher来发送event
         eventPublisher.publishEvent(event);
         // 也可以直接使用
         // applicationContext.publishEvent(event)
         return true;
     } catch (Exception e) {
         log.error("failed in publishing event", e);
     }
     return false;
 }

// pojo需要序列化
public class EventBody implements Serializable {

    private Long id;

    private String name;

}

// 监听
@Component
@Slf4j
public class MyEventListener implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        log.info("Received MyCustomRemoteEvent - message: ");
    }
}

// 定制
public class MyEvent extends RemoteApplicationEvent {

    public MyEvent() {
    }

    public MyEvent(Object body, String originService, String destinationService) {
        super(body, originService, destinationService);
    }
}
// MyEvent加载进来
@Configuration
@RemoteApplicationEventScan(basePackageClasses = MyEvent.class)
public class BusExtConfiguration {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值