【问题标题】:required configurations for Kafka ConsumerInterceptorKafka ConsumerInterceptor 所需的配置
【发布时间】:2020-11-17 02:39:59
【问题描述】:

我是卡夫卡的新手。我已经建立了我的环境来生产和消费记录。但是,我的目标是在将记录发送给目标消费者之前拦截记录并修改它们的值。 现在,为了确保环境设置良好以拦截记录,我正在编写一个简单的 ConsumerInterceptor,它将拦截记录并打印它们的值。 我的 configure() 方法应该实现什么来启用我的 consumerInterceptor?我应该添加/修改哪些其他配置以及在哪里?

public class SimpleConsumerInterceptors<K, V> implements ConsumerInterceptor<K, V>{
    private String clientId;

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

// What configurations required to enable my consumerInterceptor?
        
    }

    public ConsumerRecords<K, V> onConsume(ConsumerRecords<K, V> records) {
        ConsumerRecords<K, V> interceptRecords = records;
        for (TopicPartition partition : records.partitions()) {
            String topic = partition.topic();
            List<ConsumerRecord<K, V>> recordsInPartition = records.records(partition);
            for (ConsumerRecord<K, V> record : recordsInPartition) {
                System.out.println("onConsume:");
                System.out.println(record.value());
            }
        }
                 
        return interceptRecords;
    }

    public void onCommit(Map<TopicPartition, OffsetAndMetadata> offsets) {
        System.out.println("onCommit")
    }

    @Override
    public void close() {
        System.out.println("close")
        this.close();
    }
}

【问题讨论】:

    标签: apache-kafka spring-kafka


    【解决方案1】:

    您所要做的就是将类名添加到interceptor.classes consumer propertyConsumerConfig.INTERCEPTOR_CLASSES_CONFIG

    如果想在Kafka创建实例后配置拦截器,只需要实现configure()即可。

    传递给方法的映射是消费者属性的映射。

    所以,假设您想让日志记录成为可选;将my.interceptor.logging.enabled=true添加到消费者配置中,并在configure()方法中使用它来配置是否记录记录。

    【讨论】:

    • 您好,感谢您的回复。它回答了我的问题。但是,由于某种原因,我的拦截器无法正常工作。我会很感激你的洞察力。这就是我正在做的事情:(1)我启动消费者的命令是:\./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic ConsumerInterceptor --from-beginning --property interceptor .classes=com.interceptor.kafka.springbootkafkainterceptor.LogConsumerInterceptors
    • 我的java代码public ConsumerRecords&lt;K, V&gt; onConsume(ConsumerRecords&lt;K, V&gt; records) { ConsumerRecords&lt;K, V&gt; interceptRecords = (ConsumerRecords&lt;K, V&gt;) new ConsumerRecords&lt;&gt;( ImmutableMap.of( new TopicPartition("ConsumerInterceptor", 1), Arrays.asList( new ConsumerRecord&lt;&gt;( "ConsumerInterceptor", 1, 1, 1l, TimestampType.CREATE_TIME, 1l,10, 10, "key", "123")))); return interceptRecords; }
    • 不要把代码放在cmets中;如你看到的;很难阅读;我以为你的问题是关于 Spring 的(这就是你标记它的方式),但你正在使用控制台使用者。控制台消费者没有办法使用拦截器,只有kafka-clients中的Java消费者。
    • 感谢您的信息,很抱歉将我的代码放在评论中。我最终需要编写一个 KafkaConsumer,但我想我会先测试拦截是否通过命令行起作用。所以我会写 KafkaConsumer 。 (我还发现你添加了一个 RecordInterceptor 可能对我的用例更好。所以我也会尝试一下)正如我所说我是 Kafka 的新手。会尽快回复你。谢谢
    • 谢谢你,我写了我的 kafka spring 消费者,并按照你之前对拦截器的指示,它正在工作
    猜你喜欢
    • 2022-12-26
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多