如何使用 Akka Java 从非演员 类 的接待员处访问演员?

How to access actors from receptionist in non-actor classes using Akka Java?

作为具有不同类型的 Akka 系统的一部分,我有不同的参与者 运行。我如何使用接待员从具有系统对象的非演员 class 中找到演员。我没有直接参考或任何方式将参考传递给非演员 class.

这是 Akka 与 actor 系统之外的 actor 交互的文档。

Java 有一个选项卡。

https://doc.akka.io/docs/akka/current/typed/interaction-patterns.html#request-response-with-ask-from-outside-an-actor

它看起来像(如果 Java 很糟糕,我们深表歉意):

// TargetActor.Command is just a placeholder
ActorSystem<Void> system;
ServiceKey<TargetActor.Command> key;

CompletionStage<Receptionist.Listing> result =
    AskPattern.ask(
        system.receptionist(),
        replyTo -> Receptionist.find(key, replyTo),
        Duration.ofSeconds(10),  // ask will fail if no reply received in this time
        system.scheduler()
    );

然后您可以使用通常的 CompletionStage 方法(例如 whenComplete 和朋友)提取 Receptionist.Listing 并采取适当的行动。

Thankfully I could come up with generic and elegant solution using Java AKKA and Receptionist !!

private <T> CompletableFuture<ActorRef<T>> findActor(ActorSystem<Void> system, ServiceKey<T> actorKey) {
    ActorRef<Command> receptionist = system.receptionist();
    Duration askTimeout = Duration.ofSeconds(3);
    CompletionStage<Listing> result = AskPattern.ask(
            receptionist,
            replyTo -> Receptionist.find(actorKey, replyTo),
            askTimeout,
            system.scheduler());

    return result.toCompletableFuture().thenApplyAsync(
            (reply) -> {
                if (reply != null && reply instanceof Listing) {
                    return reply.getServiceInstances(actorKey).stream().findFirst().get();
                }
                return null;
            }).exceptionally((Throwable ex) -> {
                return null;
            });
}