Search code examples
javaakka

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


I have different actors running as part of Akka systems having different types. How can I find an actor from non-actor class having System object using receptionist. I don't have direct reference or any way to pass the reference to non-actor class.


Solution

  • 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;
                });
    }