简体   繁体   English

关闭卡夫卡消费者

[英]Shutting down Kafka Consumer

I was reading up details of Kafka High level consumer in this link and saw the below statement - 我在此链接中阅读了Kafka高级消费者的详细信息,并看到以下声明-

In practice, a more common pattern is to use sleep indefinitely and use a shutdown hook to trigger clean shutdown. 实际上,更常见的模式是无限期地使用睡眠并使用关闭钩子来触发干净关闭。

Are there any examples for doing this or pointers which could help? 是否有任何执行此操作的示例或有帮助的指针?

This will be an example of an infinite loop 这将是一个无限循环的例子

public void run() {
    try {
      consumer.subscribe(topics);
      while (true) {
          ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
        //do something
      }
    } catch (WakeupException e) {
      // do nothing we are shutting down 
    } finally {
      consumer.close();
    }
  }

  public void shutdown() {
    consumer.wakeup();
  }
}

And this will be your shutdown hook. 这将是您的关机钩子。

@PostConstruct
    private void init(){
        addShutdownHook(); 
    }

 private void addShutdownHook(){
   Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

            @Override
            public void run() {
                shutdown();
            }
        }));
    }

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

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