You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Spring-Pulsar消费Apache Pulsar主题中的空负载消息?

解决Spring-Pulsar监听空负载(墓碑消息)的问题

你遇到的核心问题是:当Pulsar发送空负载的墓碑消息时,Spring的MessageBuilder会触发断言失败——即便你在@Payload上设置了required=false,它默认仍会校验负载非空。以下是两种可行的解决方案:

方案1:全局关闭负载非空断言

在Spring Boot配置文件中添加参数,禁用Spring Messaging的消息负载非空校验:

spring.pulsar.listener.message-builder-assertions-enabled=false

配置生效后,空负载消息能正常进入监听方法,此时@Payload标注的jsonString会为null,你可以直接通过if (jsonString == null)判断并处理墓碑消息。

方案2:使用Pulsar原生Message对象接收

如果不想修改全局配置,可直接在监听方法中接收Pulsar原生的Message对象,绕过Spring Messaging的封装逻辑:

@PulsarListener(
    subscriptionName = "hello-pulsar-sub-2",
    topics = "#{dataAssetService.getCompactedTopicsArray()}",
    properties = {"readCompacted=true"}
)
public void consumeEntireTopic(Message<String> message) throws IOException {
    String jsonString = message.getValue();
    String topic = message.getTopicName();
    String key = message.getKey();
    long publishTime = message.getPublishTime();
    
    if (jsonString == null) {
        // 处理Key被删除的墓碑消息逻辑
    } else {
        // 处理正常消息逻辑
    }
}

这种方式直接操作Pulsar原生对象,不受Spring Messaging断言限制,能直接获取空负载。

内容的提问来源于stack exchange,提问作者Konrad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:14:53