Spring Boot Manual对kafka消息的确认不起作用

时间:2019-03-25 15:42:54

标签: spring-boot apache-kafka kafka-consumer-api

我有一个spring boot kafka使用者,它使用主题中的数据并将其存储在数据库中并在存储后确认。 它工作正常,但是如果应用程序在使用记录后无法获得数据库连接,则会出现问题,在这种情况下,我们不会发送确认,但消息仍然不会消耗,直到或除非我们更改组标识并重新启动使用方

我的消费者如下所示

  @KafkaListener(id = "${group.id}", topics = {"${kafka.edi.topic}"})
  public void onMessage(ConsumerRecord record, Acknowledgment acknowledgment) {
      boolean shouldAcknowledge = false;
      try {
          String tNo = getTrackingNumber((String) record.key());

          log.info("Check Duplicate By Comparing With DB records");

          if (!ediRecordService.isDuplicate(tNo)) {---this checks the record in my DB
              shouldAcknowledge = insertEDIRecord(record, tNo); --this return true
          } else {
              log.warn("Duplicate record found.");
              shouldAcknowledge = true;
          }
          if (shouldAcknowledge) {
              acknowledgment.acknowledge();
          }```



So if you see the above snippet we did not sent acknowledgment.

1 个答案:

答案 0 :(得分:1)

kafka偏移量不是这样工作的here

每个分区中的记录都分配有一个顺序ID号,称为偏移量,可唯一标识分区中的每个记录。

从上面的语句中获取信息,例如,从第一个民意调查消费者处获得偏移量为300的消息,并且由于某些问题而未能将其持久保存到数据库中并且不会提交偏移量。

因此,在下一次轮询中,它将获得下一条偏移量为301的下一条记录,如果它成功将数据持久保存到数据库中,则它将提交偏移量301 (这意味着所有记录在分区将一直处理到该偏移量,在上面的示例中为301)

解决方案:使用重试机制,直到成功地将数据存储到数据库中并进行一些有限的重试,或者将失败的数据保存到error topic中,然后再进行处理,或者将失败的记录的偏移量保存在某个位置,以便以后可以重新处理他们。