【问题标题】:Kafka Streams produce messages conditionally after transformationKafka Streams 转换后有条件地产生消息
【发布时间】:2021-01-18 01:32:35
【问题描述】:

我们有一个用例,我们必须将一些消息读入 KStreams,然后转换消息并有条件地将其生成到另一个主题。

在我们的用例中,为了转换对象,我们进行了下游 API 调用。如果 API 调用成功,则生成到 newTopic1,否则生成到 newTopic2。怎样才能达到同样的效果??

截至目前,我们正在使用 Streams API 提供的 to 方法使用以下样式为新的 Kafka 主题生成丰富的(即转换的对象)。

KStream<String, Customer> transformedStream = sourceKafkaStream
                .mapValues(cust -> {
                    try {
                        logger.info("Hitting to the downstream to fetch additional information, will take few seconds.");
                        Thread.sleep(7000);
                        return RecordEnrichmentAndTransformationBuilder.enrichTheCustomer(cust);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return cust;
                });
                .to('newTopic1', Produced.with(AppSerdes.String(), AppSerdes.serdeForEnrichedCustomer()));

感谢对此的回应。

【问题讨论】:

    标签: apache-kafka apache-kafka-streams spring-kafka kafka-producer-api


    【解决方案1】:

    使用 DSL api,您使用 KStream::filterKStream:to(TopicNameExtractor&lt;K, V&gt; topicExtractor, Produced&lt;K, V&gt; produced)

    如果两种格式相同,示例代码将如下所示:

    KStream<String, Customer> transformedStream = sourceKafkaStream
                    .mapValues(cust -> {
                        try {
                            logger.info("Hitting to the downstream to fetch additional information, will take few seconds.");
                            Thread.sleep(7000);
                            return RecordEnrichmentAndTransformationBuilder.enrichTheCustomer(cust);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return cust;
                    });
                    .to((key, value, recordContext) -> topicNameCalculation(key, value), Produced.with(AppSerdes.String(), AppSerdes.serdeForEnrichedCustomer()));
    

    topicNameCalculation(...) 将根据键和值选择正确的主题。

    一个通知 一般来说,在 Kafka Streams 中进行外部调用并不是一个好方法。

    【讨论】:

    • 感谢@Bartosz 的回答。您能否详细说明为什么在 Kafka 流中进行外部调用不是一个好主意。我会欣赏你可能拥有的设计理念。我们正在广泛计划通过外部 API 调用来征收流。
    • @AdityaGoel,有几个原因,例如: - 如果调用将持续“太”长,可能会发生重新平衡 - 如果调用不是幂等的,则可能会破坏业务逻辑。 Kafka Streams 可以为同一条消息多次调用调用(仅在 Kafka 中只调用一次)。
    • 感谢您的回答。有没有办法控制流任务的超时/心跳时间?
    • @AdityaGoel,你可以控制这一切。
    • 这个属性 max.poll.interval.ms 不是默认为 Integer.MAX_VALUE 吗? @Bartosz
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-02-28
    • 2021-07-13
    相关资源
    最近更新 更多