kafka消费者客户端自定义拦截器

本文深入探讨Kafka消费者客户端的拦截器机制,通过实现ConsumerInterceptor接口,展示如何自定义消息处理逻辑,包括修改消息内容及跟踪消费位移。同时提供了一个具体的示例代码,演示了如何使用自定义拦截器修改消息值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

与生产者客户端拦截器机制一样,kafka消费者客户端中也定义了拦截器逻辑,通过实现ConsumerInterceptor来实现自定义拦截器逻辑,ConsumerInterceptor主要有三个方法:

public ConsumerRecords<String, String> onConsume(ConsumerRecords<String, String> records)
consumer会在poll方法返回之前调用此方法,来对消息进行定制化的操作,比如修改消息内容,按照一定规则过滤消息等。

public void onCommit(Map<TopicPartition, OffsetAndMetadata> offsets)
consumer会在提交消费位移之后调用此方法,可以在此方法中跟踪提交位移的相关信息。

实现消费者客户端自定义拦截器示例代码:

public class MyConsumerInterceptor implements ConsumerInterceptor<String,String> {
    @Override
    public ConsumerRecords<String, String> onConsume(ConsumerRecords<String, String> records) {
        Map<TopicPartition, List<ConsumerRecord<String, String>>> newRecords = new HashMap<>();
        for(TopicPartition partition:records.partitions()){
            List<ConsumerRecord<String, String>> recs = records.records(partition);
            List<ConsumerRecord<String, String>> newRecs = new ArrayList<>();
            for(ConsumerRecord<String,String> rec:recs){
                String newValue = "interceptor-"+rec.value();
                ConsumerRecord<String,String> newRec = new ConsumerRecord<>(rec.topic(),
                        rec.partition(),rec.offset(),rec.key(),newValue);
                newRecs.add(newRec);
            }
            newRecords.put(partition,newRecs);
        }
        return new ConsumerRecords<>(newRecords);
    }
    @Override
    public void onCommit(Map<TopicPartition, OffsetAndMetadata> offsets) {
       offsets.forEach((tp,offsetAndMetadata) -> {
           System.out.println(tp+" : "+offsetAndMetadata.offset());
        });
    }
    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }

另外在消费者客户端配置中增加如下配置:

properties.setProperty(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG,MyConsumerInterceptor.class.getName())

运行后结果如下:
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值