我们将通过展示一个以响应式方式生成和消费的示例Spring Boot应用程序,快速了解Spring对Apache Pulsar的响应式支持。这是一个完整的应用程序,不需要任何额外的配置,只要您在默认位置localhost:6650上运行Pulsar集群即可。
1. Dependencies
Spring Boot应用程序只需要Spring Boot启动器脉冲响应依赖关系。以下清单分别显示了如何定义Maven和Gradle的依赖关系:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-pulsar-reactive</artifactId>
<version>4.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
2. Application Code
以下是应用程序源代码:
@SpringBootApplication
public class ReactiveSpringPulsarHelloWorld {
public static void main(String[] args) {
SpringApplication.run(ReactiveSpringPulsarHelloWorld.class, args);
}
@Bean
ApplicationRunner runner(ReactivePulsarTemplate<String> pulsarTemplate) {
return (args) -> pulsarTemplate.send("hello-pulsar-topic", "Hello Reactive Pulsar World!").subscribe();
}
@ReactivePulsarListener(subscriptionName = "hello-pulsar-sub", topics = "hello-pulsar-topic")
Mono<Void> listen(String message) {
System.out.println("Reactive listener received: " + message);
return Mono.empty();
}
}
就是这样,只需几行代码,我们就有了一个可用的Spring Boot应用程序,它以响应式方式生成和使用Pulsar主题的消息。
启动后,应用程序使用ReactivePulsarTemplate向hello pulser主题发送消息。然后,它使用@ReactivePulsarListener从hello脉冲星主题中消费。
简单性的关键因素之一是Spring Boot启动器,它可以自动配置并向应用程序提供所需的组件