Spring Cloud Stream Kafka发送POJO类报ClassCastException异常求助
问题解决方法
错误根因
你遇到的类转换异常(字节数组[B无法转为com.msg.bt.Grade)本质是消费端没有正确将Kafka中存储的JSON字节数据反序列化为目标POJO对象,具体问题出在两处:
- 配置路径错误:
spring.json相关的反序列化配置直接放在yml根路径不会被Spring Cloud Stream Kafka binder识别,需要绑定到对应消费端的配置项中才会生效 - 类全限定名不匹配:异常中实际的Grade类路径是
com.msg.bt.Grade,但你配置的默认反序列化类型是com.msg.Grade,少了bt包层级,反序列化无法定位到正确类
解决方案
第一步:修正application.yml配置
按如下内容调整配置,重点修正类路径、将反序列化配置绑定到对应消费端:
spring: application: name: kafka-messaging cloud: function: definition: random;publish;log stream: bindings: random-out-0: destination: random-topic-2 content-type: application/json # 生产端显式指定消息类型为JSON publish-in-0: destination: random-topic-2 group: mypublish-reader-group content-type: application/json # 消费端指定接收JSON格式 publish-out-0: destination: message-topic-2 log-in-0: destination: message-topic-2 group: message-reader-group kafka: binder: brokers: localhost:9092 bindings: publish-in-0: consumer: # 配置JSON反序列化规则 configuration: spring.json.trusted.packages: com.msg.bt spring.json.value.default.type: com.msg.bt.Grade
第二步:确认Grade类符合序列化要求
保证com.msg.bt.Grade类具备无参构造函数、所有成员变量有对应的getter/setter方法,Jackson可正常完成序列化/反序列化操作。
可选方案:使用Kafka原生反序列化
如果你想用Kafka原生的反序列化能力,可调整配置如下:
spring: cloud: stream: kafka: bindings: publish-in-0: consumer: use-native-decoding: true # 开启原生解码 configuration: value.deserializer: org.springframework.kafka.support.serializer.JsonDeserializer spring.json.trusted.packages: com.msg.bt spring.json.value.default.type: com.msg.bt.Grade
调整后重启服务即可正常消费POJO类型消息。
内容的提问来源于stack exchange,提问作者jka
相关产品推荐
相关产品推荐

