How to skip corrupt (non-serializable) messages in Spring Kafka Consumer?

前端 未结 2 437
暖寄归人
暖寄归人 2021-01-12 09:12

This question is for Spring Kafka, related to Apache Kafka with High Level Consumer: Skip corrupted messages

Is there a way to configure Spring Kafka consumer to ski

相关标签:
2条回答
  • 2021-01-12 09:52

    You need ErrorHandlingDeserializer: https://docs.spring.io/spring-kafka/docs/2.2.0.RELEASE/reference/html/_reference.html#error-handling-deserializer

    If you can't move to that 2.2 version, consider to implement your own and return null for those records which can't be deserialized properly.

    The source code is here: https://github.com/spring-projects/spring-kafka/blob/master/spring-kafka/src/main/java/org/springframework/kafka/support/serializer/ErrorHandlingDeserializer2.java

    0 讨论(0)
  • 2021-01-12 09:55

    In case you are using older version of kafka, in a @KafkaListener set the following Consumer factory configurations.

     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, CustomDeserializer.class);
    

    Here is the code for CustomDeserializer:

     import java.util.Map;
        import org.apache.kafka.common.serialization.Deserializer;
        import com.fasterxml.jackson.databind.ObjectMapper;
        public class CustomDeserializer implements Deserializer<Object>
        {
            @Override
            public void configure( Map<String, ?> configs, boolean isKey )
            {
            }
    
            @Override
            public Object deserialize( String topic, byte[] data )
            {
                ObjectMapper mapper = new ObjectMapper();
                Object object = null;
                try
                {
                    object = mapper.readValue(data, Object.class);
                }
                catch ( Exception exception )
                {
                    System.out.println("Error in deserializing bytes " + exception);
                }
                return object;
            }
    
            @Override
            public void close()
            {
            }
        }
    
    

    Since I want my code to be generic enough to read any kind of json, object = mapper.readValue(data, Object.class); I am converting it to Object.class. And as we are catching exception here, it won't be retried once read.

    0 讨论(0)
提交回复
热议问题