Spring Kafka JsonDesirialization MessageConversionException 未能解析类名 Class not found

CRO*_*OSP 10 spring apache-kafka json-deserialization spring-boot spring-kafka

我有两个服务应该通过Kafka. 让我们调用第一个服务WriteService和第二个服务QueryService

WriteService端,我对生产者有以下配置。

@Configuration
public class KafkaProducerConfiguration {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        // list of host:port pairs used for establishing the initial connections to the Kakfa cluster
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
                bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                JsonSerializer.class);

        return props;
    }

    @Bean
    public ProducerFactory<String, Object> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, Object> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试发送类的对象 com.example.project.web.routes.dto.RouteDto

QueryService端,消费者配置定义如下。

@Configuration
@EnableKafka
public class KafkaConsumerConfiguration {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.groupid}")
    private String serviceGroupId;

    @Value("${spring.kafka.consumer.trusted-packages}")
    private String trustedPackage;

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                bootstrapServers);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                JsonDeserializer.class);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, serviceGroupId);
        props.put(JsonDeserializer.TRUSTED_PACKAGES, trustedPackage);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return props;
    }

    @Bean
    public ConsumerFactory<String, Object> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Object> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());

        return factory;
    }

}
Run Code Online (Sandbox Code Playgroud)

侦听器具有以下定义。有效载荷类具有完全限定名称 -com.example.project.clientqueryview.module.routes.messaging.kafka.RouteDto

@KafkaListener(topics = "${spring.kafka.topics.routes}",
            containerFactory = "kafkaListenerContainerFactory")
    public void listenForRoute(ConsumerRecord<String, RouteDto> cr,
                               @Payload RouteDto payload) {
        logger.info("Logger 1 [JSON] received key {}: Type [{}] | Payload: {} | Record: {}", cr.key(),
                typeIdHeader(cr.headers()), payload, cr.toString());
    }

    private static String typeIdHeader(Headers headers) {
        return StreamSupport.stream(headers.spliterator(), false)
                .filter(header -> header.key().equals("__TypeId__"))
                .findFirst().map(header -> new String(header.value())).orElse("N/A");
    }
Run Code Online (Sandbox Code Playgroud)

发送消息时,我收到以下错误

引起:org.springframework.messaging.converter.MessageConversionException:无法解析类名。找不到类 [com.example.project.web.routes.dto.RouteDto]; 嵌套异常是 java.lang.ClassNotFoundException: com.example.project.web.routes.dto.RouteDto

错误已经足够清楚了。但是我不明白为什么默认情况下它有这种行为。我不希望在不同的服务中有相同的包,这完全没有意义。

我还没有找到禁用此功能并使用提供给侦听器的类的方法,并带有注释 @Payload

如何在不手动配置映射器的情况下解决这个问题?

Dea*_*ool 8

如果您使用的是 spring-kafka-2.2.x,您可以通过重载的文档构造函数禁用默认标头JsonDeserializer

从版本 2.2 开始,您可以通过使用具有布尔值 useHeadersIfPresent(默认情况下为 true)的重载构造函数之一,显式配置反序列化器以使用提供的目标类型并忽略标头中的类型信息。以下示例显示了如何执行此操作:

DefaultKafkaConsumerFactory<String, Object> cf = new DefaultKafkaConsumerFactory<>(props,
    new IntegerDeserializer(), new JsonDeserializer<>(Cat1.class, false));
Run Code Online (Sandbox Code Playgroud)

如果使用较低版本,则使用MessageConverter(您可能会从 spring-kafka-2.1.x 及更高版本中看到此问题)

Spring for Apache Kafka 通过 MessagingMessageConverter 实现及其 StringJsonMessageConverter 和 BytesJsonMessageConverter 自定义提供 MessageConverter 抽象。您可以直接将 MessageConverter 注入到 KafkaTemplate 实例中,也可以使用 @KafkaListener.containerFactory() 属性的 AbstractKafkaListenerContainerFactory bean 定义。以下示例显示了如何执行此操作:

@Bean
 public KafkaListenerContainerFactory<?> kafkaJsonListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, RouteDto> factory =
    new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setMessageConverter(new StringJsonMessageConverter());
return factory;
  }

  @KafkaListener(topics = "jsonData",
            containerFactory = "kafkaJsonListenerContainerFactory")
    public void jsonListener(RouteDto dto) {
     ...
   }
Run Code Online (Sandbox Code Playgroud)

注意:只有在方法级别声明了@KafkaListener 注解,才能实现这种类型推断。对于类级别的@KafkaListener,有效负载类型用于选择要调用的@KafkaHandler 方法,因此在选择方法之前必须已经转换了它。