繁体   English   中英

消费者中的 Kafka 消息处理

[英]Kafka message handling in consumer

我有一个消费者,它从一个主题中读取数据并产生一个线程进行处理。 在单个时间点,服务器中可能会处理多条消息。 应用程序遇到数据库超时并且所有正在处理的消息都丢失了。 由于有多个线程轮询 DB 连接,应用程序抛出了 memory 异常并宕机。 即使消费者在没有处理的情况下宕机,我如何改进架构以消除数据丢失

您应该在完成处理后通过提交偏移量来执行至少一次处理。 即做

  consumer.commitSync();

在您的线程成功完成后。

请注意,您还需要通过将“enable.auto.commit”设置为 false 来配置消费者以停止自动提交偏移量。

尽管您的消费者是幂等的,但您需要小心。 即如果失败,并且再次读取和处理相同的值,则不会影响结果。

从 DB 获得成功响应后,您应该提交偏移量。

该问题与可用的数据库连接和线程有关。 处理此问题的唯一方法是获取数据库连接,然后将数据库连接发送到线程。

线程示例

public class ConsumerThreadHandler implements Callable {

    private ConsumerRecord consumerRecord;
    private Connection dataBaseConnection;

    public ConsumerThreadHandler(ConsumerRecord consumerRecord,) {
        this.consumerRecord = consumerRecord;
        this.dataBaseConnection = dataBaseConnection;
    }

    @Override
    public Object call() throws Exception {
        // Perform all the data base related things
        // and generate the proper response
        return;
    }
}

消费者守则

 executor = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());

            while (true) {
              ConsumerRecords<String, String> records = consumer.poll(100);
              for (final ConsumerRecord record : records) {
                 // Get database connection , Check untill get the connection  or maintain the connection pool and based on available connection move next.
                Future future=executor.submit(new ConsumerThreadHandler(record,dataBaseConnection));
                if(future.isDone())
                    // Based on the proper response commit the offset
              }
            }
          }

您可以通过以下简单示例 go。

https://howtoprogram.xyz/2016/05/29/create-multi-threaded-apache-kafka-consumer/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM