Spring启动Kafka,消息中包名header

Spring Boot Kafka, package name in the message header

我有两个服务 eshopeshop-notification-service。服务 eshop 发送消息:Notification(String message, LocalDateTime timestamp) 到 Kafka 并 eshop-notification-service 使用它。

由于某种原因,在消息反序列化过程中,来自生产者的包名称 (com.example.eshop.model.Notification) 被保存在消息 headers 中,因此,消费者端的反序列化失败并出现错误:

Caused by: org.springframework.messaging.converter.MessageConversionException: failed to resolve class name. Class not found [com.example.eshop.model.Notification]; nested exception is java.lang.ClassNotFoundException: com.example.eshop.model.Notification

而消费者端正确的包路径是:com.example.eshopnotification

我该如何解决这个问题?为什么包裹保存在消息中headers?

查看此答案 -

您可以使用类型映射,或将 USE_TYPE_INFO_HEADERS 属性 设置为 false 并设置默认类型。

您也可以在生产者端设置:

JsonSerializer.ADD_TYPE_INFO_HEADERS(默认为 true):您可以将其设置为 false 以在 JsonSerializer 上禁用此功能(设置 addTypeInfo 属性)。

https://docs.spring.io/spring-kafka/docs/2.7.x/reference/html/#json-serde

在application.yml

中尝试如下映射配置
spring: 
  kafka:
    consumer:
      properties:
        spring:
          json:
            type:
              mapping: "com.example.eshop.model.Notification:com.example.eshopnotification.Notification"