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

后端 未结 2 1325
北荒
北荒 2021-02-06 03:04

I am using Spring Kafka first time and I am not able to use Acknowledgement.acknowledge() method for manual commit in my consumer code as mentioned here https://docs.spring.io/s

2条回答
  •  时光取名叫无心
    2021-02-06 03:55

    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
        }
    

提交回复
热议问题