使用 Spring for Apache Pulsar
前言
对于基于 Spring for Apache Pulsar 的应用程序,我们推荐采用“Spring Boot 优先”的方式,因为它能极大地简化工作。为此,你可以添加 spring-boot-starter-pulsar 模块作为依赖。
本参考文档的大部分内容假定读者使用 starter,并基于此给出大多数配置指引。不过,当指引特定于 Spring Boot starter 的用法时,我们会明确指出。
章节摘要
快速导览
我们将通过展示一个进行生产和消费的 Spring Boot 示例应用程序,来快速了解 Spring for Apache Pulsar。这是一个完整的应用程序,不需要任何额外配置,只要你有一个 Pulsar 集群运行在默认 位置——localhost:6650。
Pulsar 客户端
当你使用 Pulsar Spring Boot Starter 时,会得到自动配置的 PulsarClient。
消息生产
在 Pulsar 生产者端,Spring Boot 自动配置提供了一个 PulsarTemplate 用于发布记录。该 template 实现了名为 PulsarOperations 的接口,并提供通过其契约发布记录的方法。
消息消费
在 Pulsar 消费者方面,我们建议终端用户应用使用 PulsarListener 注解。要使用 PulsarListener,你需要使用 @EnablePulsar 注解。当你使用 Spring Boot 支持时,它会自动启用该 注解,并配置 PulsarListener 所需的全部组件,例如消息监听基础设施(负责创建 Pulsar 消费者)。PulsarMessageListenerContainer 使用一个 PulsarConsumerFactory 来创建并管理底层用于消费消息的 Pulsar 消费者。
发布和消费分区 topic
在以下示例中,我们发布到一个名为 hello-pulsar-partitioned 的 topic。它是一个分区 topic, 对于本示例,我们假设该 topic 已经以三个分区创建。
事务
本节介绍 Spring for Apache Pulsar 如何支持事务。
空载荷与 “Tombstone” 记录的日志压缩
使用日志压缩时,你可以发送和接收带 null 载荷的消息,以标识某个键的删除。你也可能因 其他原因收到 null 值,例如反序列化器在无法反序列化某个值时可能返回 null。