检索无法反序列化的Kafka消息的有效载荷和标头

时间:2018-10-30 17:36:02

标签: java apache-kafka spring-kafka

我正在使用spring-kafka 2.1.7来使用JSON消息,并且我想处理无法正确反序列化的消息。
为了覆盖遍历同一条消息的默认行为,我扩展了JsonDeserializer来覆盖deserialize方法。

public class CustomKafkaJsonDeserializer<T> extends JsonDeserializer<T> {

    public CustomKafkaJsonDeserializer(Class<T> targetType) {
        super(targetType);
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    }

    @Override
    public T deserialize(String topic, byte[] data) {
        try {
            return super.deserialize(topic, data);
        } catch (Exception e) {
            log.error("Problem deserializing data " + new String(data) + " on topic " + topic, e.getMessage());
            return null;
        }
    }

}

这是我的使用者及其配置:

@Service
public class Consumer {

    @KafkaListener(topics = "${kafka.topic.out}", containerFactory = "kafkaListenerContainerFactory", errorHandler = "customKafkaListenerErrorHandler")
    public void consume(@Payload Lines lines, @Headers MessageHeaders messageHeaders) {
        //treatment
    }

}

@Configuration
public class ConsumerConfig {

    ...

    @Bean
    public ConsumerFactory<String, Lines> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs(), new StringDeserializer(), new CustomKafkaJsonDeserializer<>(Lines.class));
    }

    @Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Lines>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, Lines> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    private Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", this.bootstrapServers);
        props.put("group.id", this.appName);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", CustomKafkaJsonDeserializer.class);
        props.put("security.protocol", this.securityProtocol);
        props.put("sasl.mechanism", this.saslMechanism);
        props.put("sasl.jaas.config", this.saslJaasConfig);
        return props;
    }
}

最后,我实现了自己的错误处理程序,以便将错误的数据发送到另一个主题。

@Component
public class CustomKafkaListenerErrorHandler implements KafkaListenerErrorHandler {

    @Autowired
    private KafkaErrorService kafkaErrorService;

    @Override
    public Object handleError(Message<?> message, ListenerExecutionFailedException exception) throws Exception {
        log.error("error handler for message: {} [{}], exception: {}", message.getPayload(), message.getHeaders(), exception.getMessage());
        kafkaErrorService.sendErrorToKafka(message.getPayload().toString(), exception.getMessage());
        throw new RuntimeException(exception);
    }

}

这是我收到错误消息时发生的事情:

  • CustomKafkaJsonDeserializer尝试反序列化消息并捕获异常。
  • 可以在catch块中检索有效载荷,但不能在标头中检索。返回null以提高偏移量。
  • 它进入错误处理程序的handleError方法。 message.getHeaders()返回正确的标头,但message.getPayload()返回KafkaNull对象。因此,在此步骤中,我无法同时发送有效载荷和标头。

关于如何实现此目标的任何建议?

1 个答案:

答案 0 :(得分:0)

返回包含数据和标头的丰富对象,而不是返回null。