Akka Streams自定义合并

时间:2016-04-19 16:10:57

标签: scala akka akka-stream

我是akka-streams的新手,不知道如何解决这个问题。

我有3个源流按序列ID排序。我想将具有相同ID的值组合在一起。每个流中的值可能丢失或重复。如果一个流是比其他流更快的生产者,它应该得到反压。

( [A-Z])

1 个答案:

答案 0 :(得分:0)

这个问题很老,但是我试图找到一个解决方案,但我只遇到了lightbend forum上的难题,但没有遇到可用的用例。因此,我决定实施并在此处发布示例。

我创建了3个来源sourceAsourceBsourceC,它们使用.throttle()以不同的速度发出事件。然后,我创建了一个RunnableGraph,在其中我使用Merge合并了源,并根据事件数量的滑动窗口将输出输出到了WindowGroupEventFlow Flow上。这是图形:

    sourceA ~> mergeShape.in(0)
    sourceB ~> mergeShape.in(1)
    sourceC ~> mergeShape.in(2)
    mergeShape.out ~> windowFlowShape ~> sinkShape

我在源代码中使用的类是这些:

object Domain {
  sealed abstract class Z(val id: Int, val value: String)
  case class A(override val id: Int, override val value: String = "A") extends Z(id, value)
  case class B(override val id: Int, override val value: String = "B") extends Z(id, value)
  case class C(override val id: Int, override val value: String = "C") extends Z(id, value)
  case class ABC(override val id: Int, override val value: String) extends Z(id, value)
}

这是我创建的用于对事件进行分组的WindowGroupEventFlow Flow

// step 0: define the shape
class WindowGroupEventFlow(maxBatchSize: Int) extends GraphStage[FlowShape[Domain.Z, Domain.Z]] {
  // step 1: define the ports and the component-specific members
  val in = Inlet[Domain.Z]("WindowGroupEventFlow.in")
  val out = Outlet[Domain.Z]("WindowGroupEventFlow.out")

  // step 3: create the logic
  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) {
    // mutable state
    val batch = new mutable.Queue[Domain.Z]
    var count = 0
    // var result = ""
    // step 4: define mutable state implement my logic here
    setHandler(in, new InHandler {
      override def onPush(): Unit = {
        try {
          val nextElement = grab(in)
          batch.enqueue(nextElement)
          count += 1

          // If window finished we have to dequeue all elements
          if (count >= maxBatchSize) {
            println("************ window finished - dequeuing elements ************")
            var result = Map[Int, Domain.Z]()
            val list = batch.dequeueAll(_ => true).to[collection.immutable.Iterable]
            list.foreach { tuple =>
              if (result.contains(tuple.id)) {
                val abc = result.get(tuple.id)
                val value = abc.get.value + tuple.value
                val z: Domain.Z = Domain.ABC(tuple.id, value)
                result += (tuple.id -> z)
              } else {
                val z: Domain.Z = Domain.ABC(tuple.id, tuple.value)
                result += (tuple.id -> z)
              }
            }
            val finalResult: collection.immutable.Iterable[Domain.Z] = result.map(p => p._2)
            emitMultiple(out, finalResult)
            count = 0
          } else {
            pull(in) // send demand upstream signal, asking for another element
          }
        } catch {
          case e: Throwable => failStage(e)
        }
      }
    })
    setHandler(out, new OutHandler {
      override def onPull(): Unit = {
        pull(in)
      }
    })
  }

  // step 2: construct a new shape
  override def shape: FlowShape[Domain.Z, Domain.Z] = FlowShape[Domain.Z, Domain.Z](in, out)
}

这就是我运行所有内容的方式:

object WindowGroupEventFlow {
  def main(args: Array[String]): Unit = {
    run()
  }

  def run() = {
    implicit val system = ActorSystem("WindowGroupEventFlow")
    import Domain._

    val sourceA = Source(List(A(1), A(2), A(3), A(1), A(2), A(3), A(1), A(2), A(3), A(1))).throttle(3, 1 second)
    val sourceB = Source(List(B(1), B(2), B(1), B(2), B(1), B(2), B(1), B(2), B(1), B(2))).throttle(2, 1 second)
    val sourceC = Source(List(C(1), C(2), C(3), C(4))).throttle(1, 1 second)

    // Step 1 - setting up the fundamental for a stream graph
    val windowRunnableGraph = RunnableGraph.fromGraph(
      GraphDSL.create() { implicit builder =>
        import GraphDSL.Implicits._
        // Step 2 - create shapes
        val mergeShape = builder.add(Merge[Domain.Z](3))
        val windowEventFlow = Flow.fromGraph(new WindowGroupEventFlow(5))
        val windowFlowShape = builder.add(windowEventFlow)
        val sinkShape = builder.add(Sink.foreach[Domain.Z](x => println(s"sink: $x")))

        // Step 3 - tying up the components
        sourceA ~> mergeShape.in(0)
        sourceB ~> mergeShape.in(1)
        sourceC ~> mergeShape.in(2)
        mergeShape.out ~> windowFlowShape ~> sinkShape

        // Step 4 - return the shape
        ClosedShape
      }
    )
    // run the graph and materialize it
    val graph = windowRunnableGraph.run()
  }
}

您可以在输出中看到我如何对具有相同ID的元素进行分组:

sink: ABC(1,ABC)
sink: ABC(2,AB)
************ window finished - dequeuing elements ************
sink: ABC(3,A)
sink: ABC(1,BA)
sink: ABC(2,CA)
************ window finished - dequeuing elements ************
sink: ABC(2,B)
sink: ABC(3,AC)
sink: ABC(1,BA)
************ window finished - dequeuing elements ************
sink: ABC(2,AB)
sink: ABC(3,A)
sink: ABC(1,BA)