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

后端 未结 2 1290
北荒
北荒 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:42

    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 noted 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.

    0 讨论(0)
  • 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
        }
    
    0 讨论(0)
提交回复
热议问题