我们将通过展示一个生产和消费的示例Spring Boot应用程序来快速浏览Apache Pulsar的Spring。 这是一个完整的应用程序,不需要任何额外的配置,只要您在默认位置 - 上运行一个 Pulsar 集群。localhost:6650

1. 依赖关系

Spring Boot 应用程序只需要依赖项。以下列表分别显示了如何定义 Maven 和 Gradle 的依赖项:spring-boot-starter-pulsar

  • Maven

  • Gradle

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

2. 申请代码

以下列表显示了示例的 Spring Boot 应用程序案例:

@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 Boot 自动配置。 Spring Boot 为我们的应用程序自动配置多个组件。 它自动为应用程序提供生产者和使用者都使用的 。PulsarClient

Spring Boot 还会自动配置,我们将其注入应用程序并开始向 Pulsar 主题发送记录。 应用程序将消息发送到名为 的主题。 请注意,应用程序不会指定任何架构信息,因为 Spring for Apache Pulsar 库会自动从您发送的数据类型推断架构类型。PulsarTemplatehello-pulsar

我们使用注释从发布数据的主题中消费。 是一个方便的注解,用于包装 Spring for Apache Pulsar 的消息监听器容器基础设施。 在后台,它创建了一个消息侦听器容器来创建和管理 Pulsar 消费者。 与常规的 Pulsar 使用者一样,使用时的默认订阅类型是模式。 当记录发布到主题中时,它们会使用它们并在控制台上打印它们。 在本例中,该框架还从该方法用作有效负载的数据类型 — 中推断出使用的架构类型。PulsarListenerhello-pulsarPulsarListenerPulsarListenerExclusivehello-pulsarPulsarlistenerPulsarListnerString