快速浏览

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

1. 依赖项

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

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

2. 应用程序代码

以下代码示例展示了Spring Boot应用程序的案例:spring-doc.cadn.net.cn

@SpringBootApplication
public class PulsarBootHelloWorld {

    public static void main(String[] args) {
        SpringApplication.run(PulsarBootHelloWorld.class, args);
    }

    @Bean
    ApplicationRunner runner(PulsarTemplate<String> pulsarTemplate) {
        return (args) -> pulsarTemplate.send("hello-pulsar-topic", "Hello Pulsar World!");
    }

    @PulsarListener(subscriptionName = "hello-pulsar-sub", topics = "hello-pulsar-topic")
    void listen(String message) {
        System.out.println("Message Received: " + message);
    }
}

让我们快速浏览一下这个应用程序的高级细节。 在文档的后面部分,我们会更详细地查看这些组件。spring-doc.cadn.net.cn

在前面的示例中,我们很大程度上依赖于 Spring Boot 自动配置。 Spring Boot 会为我们的应用程序自动配置几个组件。 它会自动提供一个 PulsarClient,该值用于生产者和消费者之间。spring-doc.cadn.net.cn

Spring Boot 也自动配置了 PulsarTemplate,我们将其注入到应用程序中并开始向 Pulsar 主题发送记录。 该应用程序向名为 hello-pulsar 的主题发送消息。 注意,该应用程序不指定任何模式信息,因为 Spring for Apache Pulsar 库会从发送数据的类型自动推断模式类型。spring-doc.cadn.net.cn

We use the PulsarListener annotation to consume from the hello-pulsar topic where we publish the data. PulsarListener is a convenience annotation that wraps the message listener container infrastructure in Spring for Apache Pulsar. Behind the scenes, it creates a message listener container to create and manage the Pulsar consumer. As with a regular Pulsar consumer, the default subscription type when using PulsarListener is the Exclusive mode. As records are published in to the hello-pulsar topic, the Pulsarlistener consumes them and prints them on the console. The framework also infers the schema type used from the data type that the PulsarListner method uses as the payload — String, in this case.spring-doc.cadn.net.cn