消息总线Bus #

一、Bus概述 #

1.1 什么是Spring Cloud Bus #

Spring Cloud Bus用于在微服务之间传播状态变化,如配置刷新事件。

text
┌─────────────────────────────────────────────────────────────┐
│                    Bus架构                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│   │  服务实例A  │  │  服务实例B  │  │  服务实例C  │        │
│   └──────┬──────┘  └──────┬──────┘  └──────┬──────┘        │
│          │                │                │                │
│          └────────────────┼────────────────┘                │
│                           │                                 │
│                           ▼                                 │
│                   ┌─────────────┐                          │
│                   │ Message Bus │                          │
│                   │   消息总线   │                          │
│                   └─────────────┘                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 Bus特性 #

特性 说明
配置刷新 批量刷新配置
事件传播 广播事件
消息中间件 支持RabbitMQ/Kafka

二、基本使用 #

2.1 添加依赖 #

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

2.2 配置文件 #

yaml
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  cloud:
    bus:
      enabled: true
      refresh:
        enabled: true

management:
  endpoints:
    web:
      exposure:
        include: bus-refresh

2.3 刷新配置 #

bash
curl -X POST http://localhost:8080/actuator/bus-refresh

三、端点配置 #

3.1 暴露端点 #

yaml
management:
  endpoints:
    web:
      exposure:
        include: bus-refresh,bus-env

3.2 刷新特定服务 #

bash
curl -X POST http://localhost:8080/actuator/bus-refresh/user-service:8001

四、自定义事件 #

4.1 定义事件 #

java
public class CustomEvent extends RemoteApplicationEvent {
    private String message;

    public CustomEvent() {
    }

    public CustomEvent(Object source, String originService, String message) {
        super(source, originService);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

4.2 发布事件 #

java
@Autowired
private ApplicationEventPublisher publisher;

public void publishEvent() {
    CustomEvent event = new CustomEvent(this, "user-service", "Hello");
    publisher.publishEvent(event);
}

4.3 监听事件 #

java
@Component
public class CustomEventListener {

    @EventListener
    public void handleCustomEvent(CustomEvent event) {
        System.out.println("Received: " + event.getMessage());
    }
}

五、总结 #

要点 说明
配置刷新 批量刷新配置
事件传播 广播事件
端点 bus-refresh

接下来让我们学习 异步通信实战

最后更新:2026-03-28