跳到主要内容
版本:2.0.7

快速导览

Doubao 中英对照 Quick Tour

目录

我们将通过展示一个进行生产和消费的 Spring Boot 示例应用程序,来快速了解 Spring for Apache Pulsar。这是一个完整的应用程序,不需要任何额外配置,只要你有一个 Pulsar 集群运行在默认位置——localhost:6650。

1. 依赖​

Spring Boot 应用程序只需 spring-boot-starter-pulsar 依赖。以下清单分别展示了如何为 Maven 和 Gradle 定义该依赖:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-pulsar</artifactId>
<version>4.0.6</version>
</dependency>
</dependencies>

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 topic 发送记录。应用程序向名为 hello-pulsar 的 topic 发送消息。注意,应用程序没有指定任何 schema 信息,因为 Spring for Apache Pulsar 库会根据你所发送数据的类型自动推断 schema 类型。

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