How to use Spring Kafka's Acknowledgement.acknowledge() method for manual commit

杀马特。学长 韩版系。学妹 提交于 2019-12-03 17:29:36

You really should follow documentation:

When using manual AckMode, the listener can also be provided with the Acknowledgment; this example also shows how to use a different container factory.

@KafkaListener(id = "baz", topics = "myTopic",
          containerFactory = "kafkaManualAckListenerContainerFactory")
public void listen(String data, Acknowledgment ack) {
    ...
    ack.acknowledge();
}

There is really nowhere note that Acknowledgment is a bean. So, change your receive() @KafkaListener method signature appropriately and remove that @Autowired for suspicious Acknowledgment bean - it just doesn't exists because this object is a part (header) of each received message.

For those still looking for a solution to these errors concerning manual acknowledgment, you don't need to specify containerFactory = "kafkaManualAckListenerContainerFactory", instead you can just add:

factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);

to your receiver config just before you return the factory object.

Then you also need:

props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

in consumer config props.

So in the end your listener method can simply look like:

@KafkaListener(topics = "${spring.kafka.topic}")
    private void listen(@Payload String payload, Acknowledgment acknowledgment) {
        //Whatever code you want to do with the payload
        acknowledgement.acknowledge(); //or even pass the acknowledgment to a different method and acknowledge even later
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!