0

所以这个问题很简单,但我现在很长一段时间都找不到答案。

我对我的 Kafka 消费者进行了手动确认,在应用程序关闭之前,我想执行一些代码,然后向 Kafka 确认。所以为此我使用@PreDestroy 注释:

@PreDestroy
private void beforeShutdown() {
    //do some code
    acknowledgement.acknowledge(); //this variable is stored on class level

现在主要问题是 Kafka 消费者在执行此操作之前已关闭,因此消息实际上并没有得到确认,并且在我启动应用程序时我再次收到它们,所以我需要某种解决方法或另一种方法来指定此功能作为关机前调用的第一件事。可以在日志中看到这一点的证明:

Shutting down ExecutorService
Consumer stopped
Shutting down ExecutorService 'taskScheduler'
Shutting down ExecutorService 'applicationTaskExecutor'
EXECUTING MY CODE
[Producer clientId=producer-1] Closing the Kafka producer with timeoutMillis = 30000 ms.

如果有人有建议,请告诉。

4

1 回答 1

1

实现SmartLifeCycle并将代码放入stop(). 把豆子放在一个很高的Phase地方,这样它就停在容器之前。默认情况下,容器是同相Integer.MAX_VALUE - 100的,因此它必须高于该值。

编辑

class Listener implements SmartLifecycle { // default phase is last (after the containers for start, before for stop).

    private volatile boolean running;

    @Override
    public void start() {
        this.running = true;
    }

    @Override
    public void stop() {
        this.running = false;
    }

    @Override
    public boolean isRunning() {
        return this.running;
    }

    ...

}
于 2019-02-14T14:30:21.290 回答