快速浏览
我们将通过展示生成和使用的示例 Spring Boot 应用程序来快速浏览 Apache Pulsar 的 Spring。
这是一个完整的应用程序,不需要任何额外的配置,只要你有一个在默认位置运行的 Pulsar 集群 -localhost:6650
.
1. 依赖关系
Spring Boot 应用程序只需要spring-boot-starter-pulsar
Dependency。以下列表分别显示了如何定义 Maven 和 Gradle 的依赖项:
-
Maven
-
Gradle
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-pulsar</artifactId>
<version>3.4.9</version>
</dependency>
</dependencies>
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-pulsar:3.4.9'
}
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
topic,则Pulsarlistener
使用它们并将其打印到控制台上。
该框架还从数据类型推断出使用的架构类型,即PulsarListner
方法用作有效负载 —String
,在这种情况下。