请编写代码实现一个Spring Cloud Bus的案例 ?
参考答案:
Spring Cloud Bus是一个用于在集群中传播消息的轻量级消息代理,通常与Spring Cloud Config一起使用,以实现配置更改的广播。以下是一个简单的Spring Cloud Bus案例,包括两个服务,它们通过Spring Cloud Bus通信以广播消息。
- 首先,在父POM中,我们需要包含Spring Cloud和Spring Boot的依赖。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.1</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- other dependencies -->
</dependencies>
- 创建第一个服务
service-bus-sender
,用于发送消息。
application.yml
spring:
application:
name: service-bus-sender
cloud:
bus:
trace:
enabled: true
stream:
kafka:
binder:
brokers: localhost:9092
bindings:
output:
destination: topic.bus
SenderApplication.java
@SpringBootApplication
public class SenderApplication {
@Autowired
private StreamBridge streamBridge;
public static void main(String[] args) {
SpringApplication.run(SenderApplication.class, args);
}
@Scheduled(fixedRate = 5000)
public void sendMessage() {
streamBridge.send("output", MessageBuilder.withPayload("Hello from service-bus-sender at " + LocalDateTime.now()).build());
}
}
- 创建第二个服务
service-bus-receiver
,用于接收消息。
application.yml
spring:
application:
name: service-bus-receiver
cloud:
bus:
trace:
enabled: true
stream:
kafka:
binder:
brokers: localhost:9092
bindings:
input:
destination: topic.bus
group: bus-receiver
ReceiverController.java
@RestController
public class ReceiverController {
@Autowired
private StreamListener streamListener;
@GetMapping("/receive")
public String receiveMessage() {
return streamListener.getLastReceivedMessage();
}
}
StreamListener.java
@Component
public class StreamListener {
private String lastReceivedMessage;
@StreamListener(target = "input")
public void handle(String message) {
this.lastReceivedMessage = message;
}
public String getLastReceivedMessage() {
return lastReceivedMessage;
}
}
- 启动两个服务,并访问
service-bus-receiver
的/receive
端点,你应该可以看到从service-bus-sender
发送过来的消息。
请注意,为了简单起见,此示例使用了Kafka作为消息代理。在实际生产环境中,你可能需要使用RabbitMQ、ActiveMQ等其他消息代理。此外,你还需要确保已经正确配置了Kafka或所选的消息代理。