简体   繁体   English

在流中发送actorRefWithAck

[英]Sending actorRefWithAck inside stream

I'm using answer from this thread because I need to treat first element especially. 我正在使用线程的答案,因为我需要特别对待第一个元素。 The problem is, I need to send this data to another Actor or persist locally (which is not possibl). 问题是,我需要将此数据发送到另一个Actor或在本地持久化(这不是可能的)。

So, my stream looks like this: 因此,我的信息流看起来像这样:

val flow: Flow[Message, Message, (Future[Done], Promise[Option[Message]])] = Flow.fromSinkAndSourceMat(
  Flow[Message].mapAsync[Trade](1) {
    case TextMessage.Strict(text) =>
      Unmarshal(text).to[Trade]
    case streamed: TextMessage.Streamed =>
      streamed.textStream.runFold("")(_ ++ _).flatMap(Unmarshal(_).to[Trade])
  }.groupBy(pairs.size, _.s).prefixAndTail(1).flatMapConcat {
    case (head, tail) =>
      // sending first element here
      val result = Source(head).to(Sink.actorRefWithAck(
        ref = actor,
        onInitMessage = Init,
        ackMessage = Ack,
        onCompleteMessage = "done"
      )).run()
      // some kind of operation on the result
    Source(head).concat(tail)
  }.mergeSubstreams.toMat(sink)(Keep.right),
  Source.maybe[Message])(Keep.both)

Is this a good practice? 这是一个好习惯吗? Will it have unintended consequences? 会产生意想不到的后果吗? Unfortunately, I cannot call persist inside stream, so I want to send this data to the external system. 不幸的是,我无法在流内部调用persist ,因此我想将此数据发送到外部系统。

Your current approach doesn't use result in any way, so a simpler alternative would be to fire and forget the first Message to the actor: 您当前的方法完全不使用result ,因此一种更简单的选择是触发并忘记向演员发送的第一条Message

groupBy(pairs.size, _.s).prefixAndTail(1).flatMapConcat {
  case (head, tail) =>
    // sending first element here
    actor ! head.head

    Source(head).concat(tail)
}

The actor would then not have to worry about handling Init and sending Ack messages and could be solely concerned with persisting Message instances. 这样,参与者就不必担心处理Init和发送Ack消息,而只需要考虑持久化Message实例。

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

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