我正在尝试从Java中的一个源广播到2个接收器,被卡在两者之间,任何指针都会有所帮助
public static void main(String[] args) {
ActorSystem system = ActorSystem.create("GraphBasics");
ActorMaterializer materializer = ActorMaterializer.create(system);
final Source<Integer, NotUsed> source = Source.range(1, 1000);
Sink<Integer,CompletionStage<Done>> firstSink = Sink.foreach(x -> System.out.println("first sink "+x));
Sink<Integer,CompletionStage<Done>> secondsink = Sink.foreach(x -> System.out.println("second sink "+x));
RunnableGraph.fromGraph(
GraphDSL.create(
b -> {
UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));
b.from(b.add(source)).viaFanOut(bcast).to(b.add(firstSink)).to(b.add(secondsink));
return ClosedShape.getInstance();
}))
.run(materializer);
}
答案 0 :(得分:1)
我对akka流图的Java api不太熟悉,所以我使用了official doc。您的代码段中有2个错误:
在将源添加到图形构建器时,需要从中获取Outlet
。因此,除了b.from(b.add(source))
之外,还应该像这样:b.from(b.add(source).out())
,根据官方文档
您不能只连续调用两个.to
方法,因为.to
期望形状为Sink
的smth,这意味着死胡同。相反,您需要将第二个接收器直接附加到bcast,像这样:
(...).viaFanOut(bcast).to(b.add(firstSink));
b.from(bcast).to(b.add(secondSink));
所有代码均应如下所示:
ActorSystem system = ActorSystem.create("GraphBasics");
ActorMaterializer materializer = ActorMaterializer.create(system);
final Source<Integer, NotUsed> source = Source.range(1, 1000);
Sink<Integer, CompletionStage<Done>> firstSink = foreach(x -> System.out.println("first sink " + x));
Sink<Integer, CompletionStage<Done>> secondSink = foreach(x -> System.out.println("second sink " + x));
RunnableGraph.fromGraph(
GraphDSL.create(b -> {
UniformFanOutShape<Integer, Integer> bcast = b.add(Broadcast.create(2));
b.from(b.add(source).out()).viaFanOut(bcast).to(b.add(firstSink));
b.from(bcast).to(b.add(secondSink));
return ClosedShape.getInstance();
}
)
).run(materializer);
最后的注释-我会三思而后行使用图API是否有意义。如果您的情况如此简单(仅2个接收器),则可能只想使用alsoTo或alsoToMat。它们使您无需使用图形就可以将多个接收器连接到流。