我正在开发Spring kafka应用程序。我正在发送一批记录。我只想在发送完所有记录后确认偏移量,而不是在每条记录之后确认。
我已经尝试了下面的代码(从此处https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/index.html#_usage_examples复制),但这可以确认每条记录之后的偏移量,而不是批次的记录。我首先设置以下属性
spring.cloud.stream.kafka.bindings.input.consumer.autoCommitOffset=false
@SpringBootApplication
@EnableBinding(Sink.class)
public class ManuallyAcknowdledgingConsumer {
public static void main(String[] args) {
SpringApplication.run(ManuallyAcknowdledgingConsumer.class, args);
}
@StreamListener(Sink.INPUT)
public void process(Message<?> message) {
Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
if (acknowledgment != null) {
System.out.println("Acknowledgment provided");
acknowledgment.acknowledge();
}
}
}
一批记录之后,我该如何手动确认?
答案 0 :(得分:1)
如您所见here,您可以接收消息列表,因此您的示例如下所示:
@StreamListener(Sink.INPUT)
public void process(List<Message<?>> messages) {
Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
if (acknowledgment != null) {
System.out.println("Acknowledgment provided");
acknowledgment.acknowledge();
}
}
在完成所有记录后,您可以调用acknowledgment.acknowledge();