• Kafka 0.10.1.0 版本开始,KafkaConsumer 就变为了双线程的设计,即用户主线程心跳线程
    • 用户主线程,就是你启动 Consumer 的那个线程
    • 心跳线程(Heartbeat Thread)只负责定期给对应的 Broker 机器发送心跳请求,以标识消费者应用的存活性(liveness)
  • Kafka Consumer 不是线程安全的,
    • 除了 KafkaConsumer#wakeup() ,其功能是来唤醒 Consumer

方案

  1. 消费者程序启动多个线程,每个线程维护专属的 KafkaConsumer 实例

    1. 每个线程负责完整的消息获取、消息处理流程
  2. 消费者程序使用单或多线程获取消息,同时创建多个消费线程执行消息处理逻辑

    1. 消息获取与消息处理过程解耦


image.png

代码实现

  1. public class KafkaConsumerRunner implements Runnable {
  2. private final AtomicBoolean closed = new AtomicBoolean(false);
  3. private final KafkaConsumer consumer;
  4. public void run() {
  5. try {
  6. consumer.subscribe(Arrays.asList("topic"));
  7. while (!closed.get()) {
  8. ConsumerRecords records =
  9. consumer.poll(Duration.ofMillis(10000));
  10. // 执行消息处理逻辑
  11. }
  12. } catch (WakeupException e) {
  13. // Ignore exception if closing
  14. if (!closed.get()) throw e;
  15. } finally {
  16. consumer.close();
  17. }
  18. }
  19. // Shutdown hook which can be called from a separate thread
  20. public void shutdown() {
  21. closed.set(true);
  22. consumer.wakeup();
  23. }
  1. private final KafkaConsumer<String, String> consumer;
  2. private ExecutorService executors;
  3. ...
  4. private int workerNum = ...;
  5. executors = new ThreadPoolExecutor(
  6. workerNum, workerNum, 0L, TimeUnit.MILLISECONDS,
  7. new ArrayBlockingQueue<>(1000),
  8. new ThreadPoolExecutor.CallerRunsPolicy());
  9. ...
  10. while (true) {
  11. ConsumerRecords<String, String> records =
  12. consumer.poll(Duration.ofSeconds(1));
  13. for (final ConsumerRecord record : records) {
  14. executors.submit(new Worker(record));
  15. }
  16. }
  17. ..