简体   繁体   English

如何在 Kafka Streams 中使用 Futures

[英]How to use Futures within Kafka Streams

When using the org.apache.kafka.streams.KafkaStreams library in Scala, I have been trying to read in an inputStream, pass that information over to a method: validateAll(infoToValidate) that returns a Future, resolve that and then send to an output stream.在 Scala 中使用org.apache.kafka.streams.KafkaStreams库时,我一直在尝试读取 inputStream,将该信息传递给一个方法: validateAll(infoToValidate)返回一个 Future,解析它,然后发送到输出流。

Example:例子:

builder.stream[String, Object](REQUEST_TOPIC)
      .mapValues(v => ValidateFormat.from(v.asInstanceOf[GenericRecord]))
      .mapValues(infoToValidate => {
        SuccessFailFormat.to(validateAll(infoToValidate))
      })

Is there any documentation on performing this?是否有任何关于执行此操作的文档? I have looked into filter() and transform() but still not sure how to deal with Futures in KStreams.我已经研究了 filter() 和 transform() 但仍然不确定如何处理 KStreams 中的 Futures。

The answer depends whether you need to preserve the original order of your messages.答案取决于您是否需要保留消息的原始顺序。 If yes, then you will have to block in one way or the other.如果是,那么您将不得不以一种或另一种方式阻止。 For example:例如:

val duration = 10 seconds // whatever your timeout should be or Duration.Inf
sourceStream
  .mapValues(x => Await.result(validate(x), duration))
  .to(outputTopic)

If however the order is not important, you can simply use a Kafka producer:但是,如果顺序不重要,您可以简单地使用 Kafka 生产者:

sourceStream
  .mapValues(x => validate(x)) // now you have KStream[.., Future[...]]
  .foreach { future =>
    future.foreach { item =>
      val record = new ProducerRecord(outputTopic, key, item)
      producer.send(record) // provided you have the implicit serializer
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM