快速浏览

我们将快速浏览 Spring 框架对 Apache Pulsar 的响应式支持,通过展示一个以响应式方式生产和消费的 Spring Boot 示例应用程序。 这是一个完整的应用程序,只要在默认位置(localhost:6650)有一个正在运行的 Pulsar 集群,就无需任何额外配置。spring-doc.cadn.net.cn

1. 依赖项

Spring Boot 应用程序只需要 spring-boot-starter-pulsar-reactive 个依赖。以下列表分别展示了如何为 Maven 和 Gradle 定义依赖关系:spring-doc.cadn.net.cn

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-pulsar-reactive</artifactId>
        <version>3.5.12</version>
    </dependency>
</dependencies>
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-pulsar-reactive:3.5.12'
}

2. 应用程序代码

这里是应用程序源代码:spring-doc.cadn.net.cn

@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();
    }
}

那就是通过几行代码,我们就有了一个能够以响应式方式从Pulsar主题生产和消费消息的Spring Boot应用。spring-doc.cadn.net.cn

一旦启动,应用程序使用一个 ReactivePulsarTemplatehello-pulsar-topic 发送消息。 它然后使用 @ReactivePulsarListenerhello-pulsar-topic 消费。spring-doc.cadn.net.cn

简化的关键之一是Spring Boot starter,它会自动配置并为应用程序提供所需的组件