快速浏览
我们将通过展示一个生成和消费的示例 Spring Boot 应用程序来快速浏览 Spring for Apache Pulsar。
这是一个完整的应用程序,不需要任何额外的配置,只要你在默认位置运行一个 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.3.7-SNAPSHOT</version>
</dependency>
</dependencies>
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-pulsar:3.3.7-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
.
请注意,应用程序没有指定任何 schema 信息,因为 Spring for Apache Pulsar 库会自动从你发送的数据类型中推断 schema 类型。
我们使用PulsarListener
注解以从hello-pulsar
我们发布数据的主题。PulsarListener
是一个方便的注解,它将消息侦听器容器基础设施包装在 Spring for Apache Pulsar 中。
在幕后,它创建了一个消息侦听器容器来创建和管理 Pulsar 消费者。
与常规 Pulsar 消费者一样,使用PulsarListener
是Exclusive
模式。
当记录发布到hello-pulsar
topic 中,Pulsarlistener
使用它们并在控制台上打印它们。
框架还从数据类型推断所使用的架构类型,其中PulsarListner
method 用作有效负载 —String
,在本例中。