快速入门

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

1. 依赖项

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

  • Maven

  • Gradle

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-pulsar</artifactId>
        <version>3.4.6-SNAPSHOT</version>
    </dependency>
</dependencies>
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-pulsar:3.4.6-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 还会自动配置 PulsarTemplate,我们将其注入到应用程序中,并开始向 Pulsar 主题发送记录。 该应用程序将消息发送到名为 hello-pulsar 的主题。 请注意,该应用程序未指定任何架构信息,因为 Spring for Apache Pulsar 库会自动从您发送的数据类型推断架构类型。

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