简体   繁体   中英

How to create multiple actors and keep a list of them in AKKA java?

I'm creating a actor system such that an actor instance needs to be assigned to every object in a list, i do this by having a String property called uri in both the object and the actor and give them the same value to figure out which actor is allocated to which object, the intention of my system is allow a another service to directly send messages to the Actor assigned to the selected object

String[]workers;
ArrayList<Actor> listOfActors = new Arraylist<Actors>();

public WorkerService(ActorSystem system) {
    for(String workerName:workers){
       final ActorRef hello =
        system.actorOf(Props.create(Actor.class),workerName);
       listOfActors.add(hello);
    }

i know the code has many flows ie the same ActorRef name for all actors, how can wokaround this? is their a way that i can distinguish the actor by its name property alone? i'm really stuck any help will be appreciated:)

Why would you use a List when a Map fits the bill?

In any event, the only time in Akka that you ever see the type Actor is when you're defining an actor's class (ie class MyActor extends Actor ). An Actor represents an actor's behavior, not an actor that other code can use (by use, I mean "send messages to", as that's basically the only thing an actor is good for), which is ultimately represented by an ActorRef . Akka Typed clears up this confusion by having Behavior and ActorRef .

String[] workers;
Map<String, ActorRef> actors = new HashMap<String, ActorRef>();

public WorkerService(ActorSystem system) {
  for (String workerName : workers) {
    if (actors.containsKey(workerName)) {
      throw new AssertionError("Should not have duplicate workers...") // or maybe an IllegalArgumentException, depending on how workers is getting set
    } else {
      ActorRef actor = system.actorOf(Props.create(WorkerActor.class), workerName);
      actors.put(workerName, actor)
    }
  }
}

Then if somewhere in your worker service you need to send a message to an actor with a given name:

ActorRef target = actors.get(name)
if (target != null) {
  target.tell(message)
}

Disclaimer, I've not really written any Java in many years, but hopefully the idea comes across.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM