如何将多个actor作为源附加到Akka流?

时间:2015-05-06 13:09:44

标签: akka akka-stream

我正在尝试构建并运行一个akka流流(在Java DSL中),其中有两个actor作为源,然后是一个合并连接,然后是一个接收器:

    Source<Integer, ActorRef> src1 = Source.actorRef(100, OverflowStrategy.backpressure());
    Source<Integer, ActorRef> src2 = Source.actorRef(100, OverflowStrategy.backpressure());
    Sink<Integer, BoxedUnit> sink = Flow.of(Integer.class).to(Sink.foreach(System.out::println));

    RunnableFlow<BoxedUnit> closed = FlowGraph.factory().closed(sink, (b, out) -> {
        UniformFanInShape<Integer, Integer> merge = b.graph(Merge.<Integer>create(2));
        b.from(src1).via(merge).to(out);
        b.from(src2).to(merge);
    });

    closed.run(mat);

我的问题是如何获取对源actor的ActorRef引用以便向它们发送消息?对于1个actor,我不会使用图形构建器,然后.run()或runWith()方法将返回ActorRef对象。但是在许多源演员的情况下该怎么办?是否有可能实现这样的流程?

1 个答案:

答案 0 :(得分:6)

在有人需要的时候回答我自己的问题。

使用jrudolph的建议,我能够使用这样的演员(在实际代码中我做了比2个ActorRefs列表更好的东西):

    Source<Integer, ActorRef> src1 = Source.actorRef(100, OverflowStrategy.fail());
    Source<Integer, ActorRef> src2 = Source.actorRef(100, OverflowStrategy.fail());
    Sink<Integer, BoxedUnit> sink = Flow.of(Integer.class).to(Sink.foreach(System.out::println));

    RunnableFlow<List<ActorRef>> closed = FlowGraph.factory().closed(src1, src2, (a1, a2) -> Arrays.asList(a1, a2), (b, s1, s2) -> {
        UniformFanInShape<Integer, Integer> merge = b.graph(Merge.<Integer>create(2));
        b.from(s1).via(merge).to(sink);
        b.from(s2).to(merge);
    });

    List<ActorRef> stream = closed.run(mat);
    ActorRef a1 = stream.get(0);
    ActorRef a2 = stream.get(1);