Create an Akka actor remotely without a new ActorS

2019-05-27 10:09发布

问题:

I've been over the documentation several times now (http://doc.akka.io/docs/akka/2.1.4/scala/remoting.html) and through the example here (https://github.com/akka/akka/tree/master/akka-samples/akka-sample-remote) and through others, and I still can't figure out how to do what I want to do. The closest answer I've found is this: how to start remote actors in scala, but it seems much more inconvenient than I'd think it would be.

I have a cluster of 12 machines to work on. I would like to something along the lines of:

val system = ActorSystem("DistributedSystem", ConfigFactor.load.getConfig("distsys"))
val master = system.actorOf(Props(new Master(...)), "master")

and then inside of the master, something along the lines of:

override def preStart() = {
    for (i <- 0 until 11) {
        // I want each of these actors to be created remotely on 
        // a different machine
        context.actorOf(Props(new RemoteChild(...)), s"child$i")
    }
}

It seems like this would be a reasonably common use case. Is there something I'm missing, or is there a good way to do this (in terms of what my configuration should look like, or how many ActorSystems I really need)? I'm just struggling to synthesize a good solution right now.

回答1:

I think what it sounds like you want to do is deploy a set of actors to a set of remote nodes and then sit them behind a local router and pass messages to the router and let it farm the work out to the remote nodes. To do that, you could try something like this:

val addresses = for(i <- 1 until 12) 
  yield AddressFromURIString(s"akka://RemoteSys@192.168.1.$i:2553")

val routerRemote = system.actorOf(Props[RemoteChild].withRouter(
  RemoteRouterConfig(RoundRobinRouter(12), addresses)))

This assumes that you have Akka running on those nodes with an ActorSystem called RemoteSys and it's using remoting configured for port 2553. When you send a message to that routerRemote ref, it will now round-robin route the messages across your 12 worker nodes.