2014-12-08 17:29:40 +01:00
|
|
|
package docs.stream.cookbook
|
|
|
|
|
|
2016-01-20 10:00:37 +02:00
|
|
|
import akka.NotUsed
|
2015-10-21 22:45:39 +02:00
|
|
|
import akka.stream.FlowShape
|
2014-12-08 17:29:40 +01:00
|
|
|
import akka.stream.scaladsl._
|
|
|
|
|
import akka.testkit.TestProbe
|
|
|
|
|
|
|
|
|
|
import scala.concurrent.Await
|
|
|
|
|
import scala.concurrent.duration._
|
|
|
|
|
|
|
|
|
|
class RecipeWorkerPool extends RecipeSpec {
|
|
|
|
|
|
|
|
|
|
"Recipe for a pool of workers" must {
|
|
|
|
|
|
|
|
|
|
"work" in {
|
|
|
|
|
val myJobs = Source(List("1", "2", "3", "4", "5"))
|
|
|
|
|
type Result = String
|
|
|
|
|
|
|
|
|
|
val worker = Flow[String].map(_ + " done")
|
|
|
|
|
|
|
|
|
|
//#worker-pool
|
2016-01-20 10:00:37 +02:00
|
|
|
def balancer[In, Out](worker: Flow[In, Out, Any], workerCount: Int): Flow[In, Out, NotUsed] = {
|
2015-11-30 15:45:37 +01:00
|
|
|
import GraphDSL.Implicits._
|
2014-12-08 17:29:40 +01:00
|
|
|
|
2015-11-30 15:45:37 +01:00
|
|
|
Flow.fromGraph(GraphDSL.create() { implicit b =>
|
2015-01-28 14:19:50 +01:00
|
|
|
val balancer = b.add(Balance[In](workerCount, waitForAllDownstreams = true))
|
|
|
|
|
val merge = b.add(Merge[Out](workerCount))
|
2014-12-08 17:29:40 +01:00
|
|
|
|
|
|
|
|
for (_ <- 1 to workerCount) {
|
|
|
|
|
// for each worker, add an edge from the balancer to the worker, then wire
|
|
|
|
|
// it to the merge element
|
|
|
|
|
balancer ~> worker ~> merge
|
|
|
|
|
}
|
|
|
|
|
|
2015-10-21 22:45:39 +02:00
|
|
|
FlowShape(balancer.in, merge.out)
|
|
|
|
|
})
|
2014-12-08 17:29:40 +01:00
|
|
|
}
|
|
|
|
|
|
2016-01-20 10:00:37 +02:00
|
|
|
val processedJobs: Source[Result, NotUsed] = myJobs.via(balancer(worker, 3))
|
2014-12-08 17:29:40 +01:00
|
|
|
//#worker-pool
|
|
|
|
|
|
2015-03-05 12:21:17 +01:00
|
|
|
Await.result(processedJobs.grouped(10).runWith(Sink.head), 3.seconds).toSet should be(Set(
|
2014-12-08 17:29:40 +01:00
|
|
|
"1 done", "2 done", "3 done", "4 done", "5 done"))
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|