简体   繁体   English

是否可以在 Future 之类的异步调用中将消息发布到 Kafka 主题?

[英]Is it possible to publish message to Kafka topics within Async calls like Future?

I want to call a method with send a kafka message to a topic inside a Future based on Failure scenario without using blocking call to maintain scalability of my application.我想调用一个方法,将 kafka 消息发送到基于失败场景的 Future 中的主题,而不使用阻塞调用来维护我的应用程序的可伸缩性。

By using Await my Future will be blocked thus using Future will lose its meaning for Async operations.通过使用 Await,我的 Future 将被阻止,因此使用 Future 将失去其对异步操作的意义。 Can kafka Stream message be published inside Futures? kafka Stream消息可以在Futures里面发布吗?

Tried Await it worked, but inside Future Kafka Stream Context was passing as null试过 Await 它有效,但在 Future Kafka Stream 中,上下文传递为 null

val actorTry: Future[ActorRef] =
  actorSystem.actorSelection(actorAddress).resolveOne()

actorTry.onComplete{
  case Success(value) =>
    value !! response
  case Failure(ex) =>
    context.forward(id, message,To.child(Sink))
}

The official Confluent java client(producer) works in an asynchronous fashion.官方 Confluent java 客户端(生产者)以异步方式工作。 Take a look to the example in the documentation:查看文档中的示例:

def produce(producer: KafkaProducer[Bytes, Book], topic: String, book: Book): Future[RecordMetadata] = { 
    val record: ProducerRecord[Bytes, Book] = new ProducerRecord(topic, book) 

    producer.send(record, new Callback { 
      override def onCompletion(metadata: RecordMetadata, exception: Exception): Unit = Option(exception) 
        .map(ex => logger error s"fail to produce record due to: ${ex.getMessage}")
        .getOrElse(logger info s"successfully produced - ${printMetaData(metadata)}")
    })
}

So, every time you produce a record a new Java Future is created.因此,每次您生成一条记录时,都会创建一个新的 Java Future。 If you need to convert the Java Future to Scala, since Scala 2.13 you can:如果您需要将 Java Future 转换为 Scala,因为 Scala 2.13 您可以:

import scala.jdk.FutureConverters._


val scalaFuture = produceResultFuture.asScala

You don´t really need Akka actors here unless you need them in more complex scenarios.你真的不需要 Akka 演员,除非你在更复杂的场景中需要他们。

To handle the result as Future, use pipeTo: https://doc.akka.io/docs/akka/2.5.32/futures.html#use-the-pipe-pattern要将结果作为 Future 处理,请使用 pipeTo: https://doc.akka.io/docs/akka/2.5.32/futures.html#use-the-pipe-pattern

Or even yo can use mapAsync from Akka stream: https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/mapAsync.html或者你甚至可以使用来自 Akka stream 的 mapAsync: https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/mapAsync.html

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

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