如何从骆驼交易卡夫卡?

时间:2018-08-14 14:20:21

标签: java apache-kafka apache-camel

我目前正在基于kafka的消息总线上工作,并由骆驼和Spring管理。我有一个XML路由定义,用于轮询事件并从看起来像这样的外部API中检索相应的完整业务对象:

`

<route id="station-event-enrich-route" autoStartup="true" >
        <from
            uri="kafka:{{kafka.cluster.url}}?brokers={{kafka.cluster.url}}&amp;topic={{events.topic.name}}&amp;autoCommitEnable=false&amp;allowManualCommit=true&amp;maxPollRecords={{station.brocker.bulk.limit}}&amp;groupId={{kafka.groupId}}" />

        <!-- SNIP logic to aggregate several events -->

        <pollEnrich strategyRef="keepHeadersAggregationStrategy">
            <simple>{{api.url}}?view=full&amp;id=$simple{in.headers.BUSINESS_ID}</simple>
        </pollEnrich>

        <!-- SNIP logic to split the retrieved events according to their ids -->

        <to uri="velocity:velocity/resource-object.vm"/>    

        <removeHeaders pattern="*" excludePattern="MANUAL_COMMIT"/>

        <to uri="kafka:{{kafka.cluster.url}}?brokers={{kafka.cluster.url}}&amp;topic={{objects.topic.name}}&amp;groupId={{kafka.groupId}}&amp;requestRequiredAcks=all" />

        <transform>
            <simple>${headers.MANUAL_COMMIT.commitSync()}</simple>
        </transform>
</route>

` 我的问题如下:当对kafka事件主题进行轮询时,并且如果pollEnrich中的api.url不可用,则不会检索任何业务对象,并且该事件将丢失。因此,我需要实现一个事务逻辑,以便能够回退路由中的初始kafka轮询,以便可以对同一事件进行多次轮询,直到api.url将等待的业务对象发送给我。

我尝试了几种方法,从将org.apache.camel:camel-kafka版本更新到2.22.0以能够进行手动提交。然后,我尝试实现一个基本的错误处理程序(配置了maximumRedeliveries = -1以进行无限次重试),以便当pollEnrich触发onException时,我可以设置标头以避免进行最终的手动提交。显然,它可以工作,但是我的事件再也不会发生。

我还尝试将事务处理的标签与spring-kafka的org.springframework.kafka.transaction.KafkaTransactionManager实例一起使用,但这不是一个好方法,因为只有生产者是事务性的。

我所缺少的是什么,正确的方法是什么?

我使用Java 8,Camel 2.22.0和Spring 4.3.18.RELEASE(不建议使用,但应该可以使用)。

2 个答案:

答案 0 :(得分:1)

它似乎是Camel中支持Kafka手动提交的一个相对较新的功能。而且文档不是特别清楚。我正在使用骆驼2.22.1。

从对问题的描述中,您正在寻找“至少一次”的语义。那就是您希望能够在出现问题时重新处理消息。当然,这种方法的结果是,分区中没有失败消息的其他消息无法被处理(或看到),直到应用程序可以成功处理它为止。在服务失败的情况下,这很可能导致给定主题的所有分区被阻止,直到备份服务为止。

Kafka uri可以使它工作: kafka:TestLog?brokers=localhost:9092&groupId=kafkaGroup&maxPollRecords=3&consumersCount=1&autoOffsetReset=earliest&autoCommitEnable=false&allowManualCommit=true&breakOnFirstError=true

将其打破:

  • kafka:TestLog:指定要从中使用的Kafka主题
  • brokers=localhost:9092:指定Kafka集群的引导服务器
  • groupId=kafkaGroup:指定Kafka消费者组
  • consumersCount=1:指定该骆驼路线的Kafka消费者数量

使用带有多个分区的Kafka主题时,最后两个配置设置很重要。它们需要进行调整/配置,以便考虑到您计划运行的Camel实例的数量。

获得“至少一次”语义的更有趣的配置:

  • autoCommitEnable=false:关闭偏移量的自动提交,以便我们可以使用手动提交。
  • allowManualCommit=true:打开手动提交,使我们能够使用KafkaManualCommit功能(请参见下面的代码)。
  • breakOnFirstError=true:如果为true,则路由将停止处理在该主题的上次民意调查中收到的批处理中的其余消息。
  • maxPollRecords=3:指定在对Kafka主题进行一次民意测验期间消耗的消息数。将其设置为较低的值可能是一个好主意,因为批量发送带有消息的消息会使批处理中的所有消息都得到重新处理。
  • autoOffsetReset=earliest:如果当前偏移量与标记分区结束的偏移量之间存在差异(稍有更多),将导致使用者从最早的偏移量读取。

骆驼路线如下所示:

      from(kafkaUrl)
        .routeId("consumeFromKafka")
        .process(exchange -> {
            LOGGER.info(this.dumpKafkaDetails(exchange));
        })
        .process(exchange -> {
            // do something
        })
        .process(exchange -> {
            // do something else
        })
        .process(exchange -> {
            exchange.setProperty(Exchange.FILE_NAME, UUID.randomUUID().toString() + ".txt");
        })
        .to("file://files")
        // at the end of the route 
        // manage the manual commit
        .process(exchange -> {
            // manually commit offset if it is last message in batch
            Boolean lastOne = exchange.getIn().getHeader(KafkaConstants.LAST_RECORD_BEFORE_COMMIT, Boolean.class);

            if (lastOne) {
                KafkaManualCommit manual =
                        exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class);
                if (manual != null) {
                    LOGGER.info("manually committing the offset for batch");
                    manual.commitSync();
                }
            } else {
                LOGGER.info("NOT time to commit the offset yet");
            }
        });

运行此路由并出现错误后,您可以使用以下命令查看使用者组的状态:

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group kafkaGroup --describe

可能会产生以下结果:

TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
TestLog 0 92 95 3

这是autoOffsetReset设置起作用的地方。当前偏移量是消费者组要从中消费的位置。如果该偏移量(92)是错误消息,则该组将落后于添加更多消息(在本例中为两个)。该路由(使用给定的设置)将使Camel继续在偏移量92处处理消息,直到成功为止。如果停止并启动骆驼路线,则应用程序将从earliest偏移量(即92)而不是latest(基于autoOffsetReset为95的latest)中获取消耗。使用from reportlab.lib.enums import TA_JUSTIFY from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Paragraph from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle doc = SimpleDocTemplate("form_letter.pdf", pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=45, leading=40, fontName="Times-Roman")) ptext = '\t\tWe&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;would&nbsp;&nbsp; like&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; to welcome&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; you to our subscriber base for Magazine! \ You will <font backcolor=green>receive</font> issues at<font size=24 color=blue name=courier backcolor=red> the excellent introductory price </font>of. Please respond by\ to start receiving your subscription and get the following free gift.' Story.append(Paragraph(ptext, styles["Justify"])) doc.build(Story) 会导致消息“丢失”,因为重新启动Camel会使用最新的偏移量开始处理。

一个可用的示例应用程序here

答案 1 :(得分:0)

如果您从此exchange.getIn()。getHeader(KafkaConstants.MANUAL_COMMIT,KafkaManualCommit.class)中获取空值

您需要在kafka uri中设置allowManualCommit = true

相关问题