Search code examples
spring-bootapache-kafkakafka-consumer-apispring-kafkaconsumer

Kafka Consumer Acknowledge message based on condition


I want that the if the control enters the if block, the mesage should be acknowledged and the statements outside if should not be read. I understand I can put an else block, just trying to understand if message has been acknowledged and it will be committed in if block, still why is the processing with the message outside if block being performed.

@Value(${environment.env})
private String env;
@kafkaListener
public void consume(@payload User user, Acknowledgment ack){
   if(!env.equals(user.getEnv()){
log.info("skip");
acknowledgement.acknowlwdge();
}
// If env same
//Do some other processing with payload
}

Have set ack mode to Manually_Immediate And also auto offset to false


Solution

  • This is simply how Java (or any computer language for that matter) works. Acknowledging the offset does just that, it can't affect the code flow that is executed within your listener.

    You need an else { ... } block.