How to create routers in akka with parameterized actors?

拜拜、爱过 提交于 2019-12-05 03:01:17

You can create routers by specifying as routees some already created actors, constructed by whatever logic.

The following example will create 2 actors created differently and then create a round robin router which will route the messages to them.

class MyActor(param1: String) extends Actor with ActorLogging {
  def receive: Actor.Receive = {
    case msg => log.info("Message from {}: {}", param1, msg)
  }
}

object MyActor {
  def apply(param: String): Props = Props(new MyActor(param))
}

object Main extends App {
  val system = ActorSystem()

  val a1 = system.actorOf(MyActor("actor1"))
  val a2 = system.actorOf(MyActor("actor2"))

  val routerProps = Props.empty.withRouter(RoundRobinRouter(routees = Vector(a1, a2)))

  val router = system.actorOf(routerProps)

  for (i <- 1 to 10) {
    router ! i
  }

  readLine()
  system.shutdown()
}

More details here: http://doc.akka.io/docs/akka/2.2.0/scala/routing.html

Venkat Alugolu
public class Master extends UntypedActor {
     -----
     -----
    public Master() {
        workerRouter = this.getContext().actorOf(Worker.createWorker().withRouter(new RoundRobinRouter(8)), "workerRouter");
    }

With Akka 2.4.2, we can simply use:

workerRouter = this.getContext().actorOf(new RoundRobinPool(noOfWorkers).props(Props.create(Worker.class)), "workerRouter");

This is best Effort code executed in min. time in akka .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!