I'm try use akka-typed in homepet project, but don't know how correct find actor or spawn and send message. My first try: wrapped "listing" from receptionist and send over adapter - very wordy and need always wear command for actor Second try: create function "tellToXXX"
private Behavior<Command> tellToWorker(ServiceKey<Worker.Command> serviceKey, Worker.Command command) {
record WrappedFindResult(Receptionist.Listing listing, Throwable failure) implements Command {
}
var system = getContext().getSystem();
getContext().pipeToSelf(
AskPattern.ask(
system.receptionist(),
replyTo -> Receptionist.find(serviceKey, replyTo),
Duration.ofSeconds(1),
system.scheduler()),
WrappedFindResult::new);
return Behaviors.receive(Command.class)
.onMessage(WrappedFindResult.class, result -> {
result.listing().getServiceInstances(serviceKey).stream().findFirst()
.orElseGet(() -> getContext().spawnAnonymous(Worker.create()))
.tell(command);
return this;
}).build();
}
how correct this? thx
Assuming that your actor is the only one that will spawn the worker actors (by implication: the workers are local), you don't need to bother with registering with the receptionist: building a
Map<ServiceKey<Worker.Command>, ActorRef<Worker.Command>>and saving that in the actor is sufficient. Then when you need a worker, look up theServiceKeyin theMap: if there isn't one, then spawn and save in the actor. If there's only oneServiceKey, then anOptional<ActorRef<Worker.Command>>works.Additionally, if there are multiple workers all doing the same job, routers may be worth considering: you spawn an actor and send it messages; the actor forwards them to a pool of workers (the behaviors of which are provided by you) which it manages.