从源创建两个接收器 - Akka Streams

时间:2018-02-02 17:01:04

标签: java akka akka-stream

我正在学习阿卡。我创建了一个整数数字源(1到100)并应用了一些流,之后我想将流分成两个接收器:一个用于偶数,另一个用于奇数但我不知道如何做到这一点。有谁能够帮我?非常感谢!请看下面的代码:

context.getSystemService(...)

1 个答案:

答案 0 :(得分:2)

这不是Java解决方案,而是使用GraphDSL方法的Scala代码段。认为它可以作为Java版本的参考:

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import akka.stream.ClosedShape
import akka.NotUsed

implicit val system = ActorSystem("Sys")
implicit val materializer = ActorMaterializer()

val source: Source[Int, NotUsed] = Source(1 to 20)

def evenFlow: Flow[Int, Int, NotUsed] =  Flow[Int].filter(_ % 2 == 0)
def oddFlow: Flow[Int, Int, NotUsed] = Flow[Int].filter(_ % 2 == 1)

val evenSink = Sink.foreach[Int](x => print(x + "e "))
val oddSink = Sink.foreach[Int](x => print(x + "o "))

val graph = GraphDSL.create() { implicit builder =>
  import GraphDSL.Implicits._

  val bcast = builder.add(Broadcast[Int](2))

  source ~> bcast.in
  bcast.out(0) ~> evenFlow ~> evenSink
  bcast.out(1) ~> oddFlow ~> oddSink

  ClosedShape
}

RunnableGraph.fromGraph(graph).run
// res1: akka.NotUsed = NotUsed
// 1o 2e 3o 4e 5o 6e 7o 8e 9o 10e 11o 12e 13o 14e 15o 16e 17o 18e 19o 20e