当前位置: 首页 > 图灵资讯 > 技术篇> Kafka批处理监听器中反序列化异常的重试策略与实现

Kafka批处理监听器中反序列化异常的重试策略与实现

来源:图灵教育
时间:2025-09-03 16:58:16

在Kafka批处理监听器中反序列化异常的重试策略和实现

本文详细介绍了如何在Spring中使用 Kafka批处理监听器中有效处理并重试反序列化异常。通过修改Defaulterrorhandler,取消对Deserializationexception的致命标记,并结合监听器内部提取和重新抛出带有null载荷的消息,实现对整批消息的重试,从而提高Kafka应用的鲁棒性。Kafka批处理监听器反序列化异常重试机制

spring 在kafka应用中,如果消费者在反序列化阶段遇到瞬时错误(例如,avro schema注册中心连接问题),默认情况下,这些deserializationexception将被视为致命错误,导致消息无法重新测试,然后可能丢失或跳过。为了提高应用程序的强度,我们需要一套机制来捕获这些异常并触发重新测试。

默认行为和挑战

Spring 当Kafka的Errorhandlingderserializer在反序列化失败时,通常会返回null作为消息载荷,并将原始异常信息存储在消息头中。然而,默认的Defaulterorhandler将Deserializationexception视为不可重试的异常类型。这意味着,即使Erorhandlingderializer捕获异常,Defaulterorhandler也不会触发新闻重试。对于批处理监听器,如果批中的任何消息反序列化失败,整个批次都可能受到影响。

实现反序列化异常重试的步骤

要实现反序列化异常的重试,我们需要分两步进行:

  1. 修改错误处理器,允许DeserializationException重试。
  2. 在监听器中识别并重新抛出反序列化异常。
1. 配置Defaulterorhandler,允许重试

Defaulterrorhandler默认将Deserializationexception标记为不可重试。我们需要通过调用removeclasification将其从致命的异常列表中删除。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer;
import org.springframework.kafka.support.serializer.SerializationUtils;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.kafka.support.serializer.DeserializationException;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;

import java.util.List;
import java.util.Map;

@Configuration
@EnableKafka
public class KafkaConfiguration {

    @Bean("myContainerFactory")
    public ConcurrentKafkaListenerContainerFactory<String, String> createFactory(
            KafkaProperties properties
    ) {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(
                new DefaultKafkaConsumerFactory<>(
                        properties.buildConsumerProperties(),
                        new StringDeserializer(),
                        new ErrorHandlingDeserializer<>(new MyDeserializer()) // 使用自定义反序列化器
                )
        );
        factory.getContainerProperties().setAckMode(
                ContainerProperties.AckMode.MANUAL_IMMEDIATE
        );

        // 创建并配置Defaulterorhandler
        DefaultErrorHandler errorHandler = new DefaultErrorHandler();
        // 将Deserializationexception的致命标记移除,这样它就可以重试了
        errorHandler.removeClassification(DeserializationException.class);
        factory.setCommonErrorHandler(errorHandler);

        return factory;
    }

    // 模拟偶尔失败的反序列化器
    static class MyDeserializer implements Deserializer<String> {
        private int retries = 0;

        @Override
        public void configure(Map<String, ?> configs, boolean isKey) {
            // No-op
        }

        @Override
        public String deserialize(String topic, byte[] bytes) {
            String s = new String(bytes);
            // 第一次模拟包含"7"字符串时抛出异常,第二次成功
            if (s.contains("7") && retries == 0) {
                retries = 1; // 标记已经尝试过一次了
                System.out.println("Simulating deserialization error for: " + s);
                throw new DeserializationException("Simulated deserialization failure for: " + s, bytes, false);
            }
            retries = 0; // 重置计数器
            System.out.println("Deserialized successfully: " + s);
            return s;
        }

        @Override
        public void close() {
            // No-op
        }
    }
}

在上述配置中,我们通过removeclasification创建了一个Defaulterrorhandler实例(DeserializationException.class)该方法明确指示Kafka,当遇到Deserializationexception时,不应将其视为致命错误,而应重试。

2. 处理监听器中的null负荷并重新抛出异常

即使defaulterorhandler被配置为允许重试derializationexception,当反序列化失败时,errorhandlingderializer仍然会向监听器发送null载荷的消息。为了触发批次重试,监听器需要检查这些null载荷,从消息头中提取原始反序列化异常,并将其重新抛出。

批处理监听器需要接收Listtt<Message<String>>而不是List<String>,以便访问消息头。

import org.springframework.stereotype.Component;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.serializer.DeserializationException;
import org.springframework.kafka.support.serializer.SerializationUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.kafka.listener.ListenerUtils;

import java.util.List;
import java.util.Objects;

@Component
public class StringListener {

    @KafkaListener(
            topics = {"string-test"},
            groupId = "test",
            batch = "true",
            containerFactory = "myContainerFactory"
    )
    public void listen(List<Message<String>> messages, Acknowledgment acknowledgment) {
        boolean hasDeserializationError = false;

        for (Message<String> message : messages) {
            String payload = message.getPayload();
            if (payload == null) {
                // 载荷为null,检查反序列化是否异常
                byte[] exceptionHeader = (byte[]) message.getHeaders().get(SerializationUtils.VALUE_DESERIALIZER_EXCEPTION_HEADER);
                if (exceptionHeader != null) {
                    DeserializationException deserializationException = 
                        ListenerUtils.byteArrayToDeserializationException(exceptionHeader);

                    if (deserializationException != null) {
                        System.err.println("Detected deserialization error for a message in batch: " + deserializationException.getMessage());
                        hasDeserializationError = true;
                        // 这里没有直接抛出,但是标记,循环结束后统一处理,确保所有信息都检查完毕
                    }
                }
            } else {
                System.out.println("Processed message: " + payload);
            }
        }

        if (hasDeserializationError) {
            // 如果批次中存在反序列化错误,重新抛出异常,触发整批重试
            System.err.println("Batch contains deserialization errors. Re-throwing to trigger retry.");
            // 抛出任何RuntimeException,defaulterrorHandler将根据配置进行重试
            throw new RuntimeException("Batch failed due to deserialization error(s).");
        }

        // 如果没有反序列化错误,或者所有错误都已经处理,不需要重试,提交偏移量
        acknowledgment.acknowledge();
        System.out.println("Batch processed and acknowledged successfully.");
    }
}

上述监听器代码:

  • 我们接收List<Message<String>>为了访问消息头。
  • 遍历批次中的每一条新闻。如果payload是null,试着从Serializationutilss开始.VALUE_DESERIALIZER_EXCEPTION_HEADER头中提取原始Deserializationexception。
  • 使用Listenerutils使用.byteArrayToDeserializationException()辅助方法将字节数组转换为Deserializationexception对象。
  • 如果检测到Deserializationexception,则设置hasderializationeron标志。
  • 在遍历了所有新闻之后,如果hasderializationeror是true,则再次抛出一个runtimeexception。这种异常将被defaulterrhandler捕获,因为我们已经从致命列表中删除了derializationexception,defaulterhandler将根据其配置的重试策略(如指数退出)重试整个批次。

注意事项:

  • 批次重试的粒度: 重新抛出异常会导致整个批次的新闻被重新测试,而不仅仅是重新测试失败的新闻。这意味着批次中成功处理的新闻也将被重新处理。在设计业务逻辑时,需要考虑权力等效性。
  • Spring Kafka版: 确保使用Spring Kafka版支持defaulterrorHandler的removeclassification方法(通常是2.8.4.可用于更高版本)。对于批处理错误处理器的分类行为,新版本(如2.9.x及更高版本)FallbackBatcherorHandler的异常分类处理更加完善。
  • 异常类型: 即使是从消息头中提取的Deserializationexception,也可以在监听器中重新抛出任何Runtimeexception。Defaulterorhandler将根据其内部的异常分类规则决定是否重新测试。
总结

通过上述配置和代码,我们成功地为Kafka批处理监听器增加了反序列化异常的重试机制。这使得应用程序能够更优雅地处理瞬时数据反序列化问题,避免消息丢失,提高系统的容错能力。在实际应用中,应根据业务需要仔细调整Defaulterorhandler的重试策略(如退出间隔、最大重试次数等),确保消息处理的力度。

以上是Kafka批处理监听器反序列化异常的重试策略和实现的详细内容。请关注图灵教育的其他相关文章!