快速入门
目录
我们将通过展示一个生产与消费消息的 Spring Boot 示例应用,快速了解 Spring for Apache Pulsar。这是一个完整的应用程序,只要你在默认位置(localhost:6650
)运行了 Pulsar 集群,就不需要任何额外的配置。
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.3</version>
</dependency>
</dependencies>
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-pulsar:3.4.3'
}
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
的主题。请注意,应用程序没有指定任何 schema 信息,因为 Spring for Apache Pulsar 库会自动从您发送的数据类型中推断出 schema 类型。
我们使用 PulsarListener
注解来消费发布数据的 hello-pulsar
主题。PulsarListener
是一个便捷的注解,它封装了 Spring for Apache Pulsar 中的消息监听器容器基础设施。在幕后,它会创建一个消息监听器容器来创建和管理 Pulsar 消费者。与常规的 Pulsar 消费者一样,使用 PulsarListener
时的默认订阅类型是 Exclusive
模式。当记录发布到 hello-pulsar
主题时,PulsarListener
会消费这些记录并将它们打印到控制台。框架还会根据 PulsarListener
方法使用的数据类型推断出所使用的 schema 类型——在本例中为 String
。