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

spring-pulsar-spring-boot-starter消费Pulsar自定义JSON对象异常排查

解决Spring Boot + Apache Pulsar自定义对象消费监听不触发的问题

核心问题分析

从日志可见Consumer已接收到消息,但@PulsarListener标注的方法未执行,大概率是自定义对象反序列化失败或Schema配置不匹配导致,以下是针对性解决方案:


1. 确保自定义User类符合JSON序列化要求

JSON反序列化框架(如Jackson)对实体类有硬性要求:

  • 必须包含无参构造器(若手动编写了带参构造器,需显式添加无参构造器)
  • 所有字段的getter和setter必须完整实现
  • 可选:用Lombok的@Data注解自动生成构造器、getter/setter,避免手写错误

修正后的User类示例:

package com.example.springpulsar;

import lombok.Data;

@Data // 自动生成无参构造器、getter、setter等方法
public class User {
    private String email;
    private String firstName;

    // 若不使用Lombok,手动添加无参构造器
    // public User() {}
}

2. 统一生产者与消费者的Schema配置

方案A:显式指定生产者的Schema

发送消息时直接指定JSON Schema,避免依赖自动推断可能出现的偏差:

public void sendMessageToPulsarTopic(User user) throws PulsarClientException {
    template.send(USER_TOPIC, user, Schema.JSON(User.class));
}

方案B:完善Spring Pulsar类型映射配置

补充完整的Pulsar服务地址,确保类型映射配置生效:

spring:
  pulsar:
    client:
      service-url: pulsar://localhost:6650
    defaults:
      type-mappings:
        - message-type: com.example.springpulsar.User
          schema-info:
            schema-type: JSON
            schema-class-name: org.apache.pulsar.client.impl.schema.JSONSchema

3. 升级Spring Pulsar版本

你当前使用的0.2.0是早期预览版本,存在自定义类型处理的已知bug。建议升级到稳定的1.x版本(如1.1.0),新版本对类型映射和@PulsarListener的兼容性更优。

修改Gradle依赖:

implementation 'org.springframework.pulsar:spring-pulsar-spring-boot-starter:1.1.0'

4. 开启详细日志排查反序列化异常

当前日志仅展示消息接收环节,未暴露反序列化过程。添加以下日志配置,查看是否有隐藏的反序列化错误:

logging:
  level:
    org.springframework.pulsar: DEBUG
    org.apache.pulsar.client.impl: TRACE

若存在反序列化异常,日志会明确提示(如缺少无参构造器、字段不匹配等)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:15:43