我们将通过展示一个生成和使用Spring Boot应用程序的示例来快速浏览Apache Pulsar的Spring。这是一个完整的应用程序,不需要任何额外的配置,只要您在默认位置localhost:6650上运行Pulsar集群即可。
1. Dependencies
Spring Boot应用程序只需要Spring Boot启动器脉冲星依赖项。以下清单分别显示了如何定义Maven和Gradle的依赖关系:
java
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-pulsar</artifactId>
<version>3.4.8-SNAPSHOT</version>
</dependency>
</dependencies>
2. Application Code
以下列表显示了该示例的Spring Boot应用程序案例:
java
@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 pulser的主题发送消息。请注意,该应用程序没有指定任何模式信息,因为Spring for Apache Pulsar库会根据您发送的数据类型自动推断模式类型。
我们使用PulsarListener注释从我们发布数据的hello pulser主题中获取数据。PulsarListener是一个方便的注释,它封装了Apache Pulsar Spring中的消息侦听器容器基础设施。在幕后,它创建了一个消息监听器容器来创建和管理Pulsar消费者。与常规Pulsar消费者一样,使用PulsarListener时的默认订阅类型是独占模式。当记录发布在hello脉冲星主题中时,Pulsarlister会消耗它们并将其打印在控制台上。该框架还从PulsarListner方法用作有效载荷的数据类型中推断出所使用的模式类型 --- 字符串,在这个case中。