将多个参与者作为源附加到Akka流

将多个参与者作为源附加到Akka流,akka,akka-stream,Akka,Akka Stream,我知道已经有人问过类似的问题: 但是我想做同样的事情,但是我不知道事先有多少来源。那么,如何动态地将多个源添加到akka流中呢 作为参考,这是另一个问题的公认答案,处理来源s1和s2: Source<Integer, ActorRef> src1 = Source.actorRef(100, OverflowStrategy.fail()); Source<Integer, ActorRef> src2 = Source.actorRef(100, Overf

我知道已经有人问过类似的问题:

但是我想做同样的事情,但是我不知道事先有多少来源。那么,如何动态地将多个源添加到akka流中呢

作为参考,这是另一个问题的公认答案,处理来源s1和s2:

 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);
Source src1=Source.actorRef(100,OverflowStrategy.fail());
Source src2=Source.actorRef(100,OverflowStrategy.fail());
Sink Sink=Flow.of(Integer.class).to(Sink.foreach(System.out::println));
RunnableFlow closed=FlowGraph.factory().closed(src1,src2,(a1,a2)->Arrays.asList(a1,a2),(b,s1,s2)->{
uniformfanishape merge=b.graph(merge.create(2));
b、 从(s1).通过(合并).到(汇);
b、 从(s2)到(合并);
});
列表流=关闭。运行(mat);
ActorRef a1=stream.get(0);
ActorRef a2=stream.get(1);
然而,在我的例子中,我在新资源上线时添加资源,在它们消失时删除它们


谢谢

如果您想动态地将源添加到正在运行的图形中,我认为MergeHub的设计就是为了做到这一点:


如果您想动态地将源添加到正在运行的图中,我认为MergeHub的设计就是为了做到这一点:

// A simple consumer that will print to the console for now
Sink<String, CompletionStage<Done>> consumer = Sink.foreach(System.out::println);

// Attach a MergeHub Source to the consumer. This will materialize to a
// corresponding Sink.
RunnableGraph<Sink<String, NotUsed>> runnableGraph =
  MergeHub.of(String.class, 16).to(consumer);

// By running/materializing the consumer we get back a Sink, and hence
// now have access to feed elements into it. This Sink can be materialized
// any number of times, and every element that enters the Sink will
// be consumed by our consumer.
Sink<String, NotUsed> toConsumer = runnableGraph.run(materializer);

Source.single("Hello!").runWith(toConsumer, materializer);
Source.single("Hub!").runWith(toConsumer, materializer);
UniqueKillSwitch killSwitch = Source.single("Hello!") // or whatever you want your source to be
    .viaMat(KillSwitches.single(), Keep.right())
    .toMat(toConsumer, Keep.left())
    .run(materializer);