如何在Spring Kafka和Spring Integration中使用GenericMessageJacksonDeserializer?

时间:2017-09-30 00:19:40

标签: spring-integration spring-kafka

如果我的kafka消息属于GenericMessage类型,我想知道如何在Spring kafka使用者工厂中使用GenericMessageJacksonDeserializer?

@Bean
public ConsumerFactory<?, GenericMessage> consumerFactory(KafkaProperties kafkaProperties) {
    final Map<String, Object> consumerProperties = kafkaProperties.buildConsumerProperties();
    final DefaultKafkaConsumerFactory<?, GenericMessage> consumerFactory = new DefaultKafkaConsumerFactory<>(consumerProperties);
    consumerFactory.setValueDeserializer(GenericMessageJacksonDeserializer.class);
    return consumerFactory;
}

1 个答案:

答案 0 :(得分:1)

  1. consumerFactory.setValueDeserializer()适用于org.apache.kafka.common.serialization.Deserializer个对象,即使不适用于课程。

  2. 我猜你的意思是org.springframework.integration.support.json.GenericMessageJacksonDeserializer 这恰好适用于ObjectMapper配置。您应该使用JacksonJsonUtils.messagingAwareMapper(),这是错误的......,我已经真正了解GenericMessageJacksonDeserializer

  3. 当你得到ObjectMapper时,你应该将它注入到... custom Deserializer实现中。已经有人用consumerFactory.setValueDeserializer()messagingAwareMapper无法按预期与org.springframework.kafka.support.serializer.JsonDeserializer一起工作,因为这一个确实需要特定类型来进行反序列化。但是我们可以尝试这样的事情:

    consumerFactory.setValueDeserializer(new JsonDeserializer(GenericMessage.class, JacksonJsonUtils.messagingAwareMapper()));