2

运行以下 akka 流式 FlowGraph 时,并非所有发出的字符都被所有接收器接收。

package sample.stream

import java.io.{ FileOutputStream, PrintWriter }
import akka.actor.ActorSystem
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl.{ Broadcast, FlowGraph, Sink, Source }
import scala.concurrent.forkjoin.ThreadLocalRandom
import scala.util.{ Failure, Success, Try }

object Sample {

  def main(args: Array[String]): Unit = {
    println("start")
    implicit val system = ActorSystem("Sys")
    import system.dispatcher
    implicit val materializer = ActorFlowMaterializer()
    var counter = -1

    val countSource: Source[Char, Unit] = Source(() => Iterator.continually { counter += 1; (counter + 'A').toChar }.take(11))

    var counter1 = 0
    val consoleSink1 = Sink.foreach[Char] { counter =>
      println("sink1:" + counter1 + ":" + counter)
      counter1 += 1
      Thread.sleep(100)
      //Thread.sleep(300)
    }
    var counter2 = 0
    val consoleSink2 = Sink.foreach[Char] { counter =>
      println("sink2:" + counter2 + ":" + counter)
      counter2 += 1
      Thread.sleep(200)
    }

    val materialized = FlowGraph.closed(consoleSink1, consoleSink2)((x1, x2) => x1) { implicit builder =>
      (console1, console2) =>
        import FlowGraph.Implicits._
        val broadcast = builder.add(Broadcast[Char](2))
        countSource ~> broadcast ~> console1
        broadcast ~> console2
    }.run()

    // ensure the output file is closed and the system shutdown upon completion
    materialized.onComplete {
      case Success(_) =>
        system.shutdown()
      case Failure(e) =>
        println(s"Failure: ${e.getMessage}")
        system.shutdown()
    }
    println("waiting the remaining ones")
    //scala.concurrent.Await.ready(materialized, scala.concurrent.duration.DurationInt(100).seconds)
    //system.shutdown()
    println("end")
  }
}

运行后生成以下输出

[info] Running sample.stream.Sample
[info] start
[info] waiting the remaining ones
[info] end
[info] sink2:0:A
[info] sink1:0:A
[info] sink1:1:B
[info] sink1:2:C
[info] sink2:1:B
[info] sink1:3:D
[info] sink2:2:C
[info] sink1:4:E
[info] sink1:5:F
[info] sink2:3:D
[info] sink1:6:G
[info] sink1:7:H
[info] sink2:4:E
[info] sink2:5:F
[info] sink1:8:I
[info] sink1:9:J
[info] sink2:6:G
[info] sink2:7:H
[info] sink1:10:K

第二个接收器没有收到第 8 个、第 9 个和第 10 个值:IJK,但整个流程仍然结束。

我应该怎么做才能等待两个接收器消耗所有数据?我发现如果我更改(x1,x2)=>x1(x1,x2)=>x2this 将等待。这与在第一个接收器中休眠 300 毫秒相同。

4

1 回答 1

5

传递给第二个参数列表的函数FlowGraph.closed确定运行流程时返回的具体化值。因此,当您传入时,(x1,x2)=>x1您返回一个未来,该未来在第一个接收器获取所有元素时完成,然后该未来上的回调关闭演员系统,而第二个接收器没有机会接收所有元素。

相反,您应该只在两个期货都完成时才将两个期货都取出并关闭系统。

您实际上可以在此处akka-stream的某些测试中看到这种方法是如何使用的。

于 2015-04-29T15:30:34.797 回答