如何在消息侦听器内停止容器?

时间:2021-04-28 07:54:24

标签: java spring spring-boot apache-kafka spring-kafka

我正在关注这个问题的答案

Spring for Kafka 2.3 setting an offset during runtime for specific listener with KafkaMessageListenerContainer

如果我收到某个偏移量,我想停止容器。如何在“onMessage”中停止容器?

另外,是否可以为容器设置初始偏移量?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是配置 ContainerStoppingErrorHandler 并抛出异常。

https://docs.spring.io/spring-kafka/docs/current/reference/html/#container-stopping-error-handlers

要停止侦听器本身中的容器,您需要在不同的线程上执行停止,以避免临时死锁。

使用 TaskExecutor,您可以使用这样的代码...

this.executor.execute(() -> container.stop());
// isRunning is false before the container.stop() waits for listener thread
int n = 0;
while (container.isRunning() && n++ < 100) { // NOSONAR magic #
    try {
        Thread.sleep(100); // NOSONAR magic #
    }
    catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
    }
}

您可以使用侦听器 KafkaListenerEndpointRegistryid bean 获取对容器的引用。

版本 2.5.11、2.6.5、2.7.0 及更高版本具有新的容器属性 stopImmediate

当为true时,监听器返回时会停止容器(之前轮询返回的额外记录将不会在容器重新启动之前传递。

对于较早的版本,或者如果它为 false,则当轮询中的所有记录都已传递给侦听器时,容器将停止。