Simple concurrency with Akka Hello World sample

I am evaluating Akka for the distributed service level, the following example prints Hello {n} 10 times, but does it one by one. As far as I understand, this is intentional for the actor, so where can I go from here to make it parallel?

import akka.actor._ object HelloActor { case class SayHello(message: String) } class HelloActor extends Actor { def receive = { case HelloActor.SayHello(message) => Thread.sleep(1000) println(message) } } object Main extends App { val system = ActorSystem("ActorSystem") val hello = system.actorOf(Props[HelloActor]) for (i <- 1 to 10) { hello ! HelloActor.SayHello(s"Hello $i") } } 

I experimented with creating several actors from the main class, but this is somehow not the case, shouldn't I just call the actor and then handle the concurrency / create more actors myself? Can anyone give an example of this (preferably to modify the above code). I read and read, but it seems to me that I need to immediately accept this, and I feel that there is simply no key concept here.

+6
source share
2 answers

In your use case, you probably want to use Routers .

For instance:

 val hello = system.actorOf(Props[HelloActor].withRouter( RoundRobinRouter(nrOfInstances = 10))) hello ! HelloActor.SayHello("Hello!") // Sends to one of the 10 

As a side note, you should avoid blocking (i.e. Thread.sleep ) in your receive method.

+4
source

As @sourcedelica notes in the comments, routing is probably what you want to do. A simple refactoring for your example using RoundRobinRouter might look like this:

 import akka.actor._ import akka.routing._ object HelloActor { case class SayHello } class HelloActor extends Actor { def receive = { case HelloActor.SayHello => println(s"saying hello from: ${self.path}") } } object Main extends App { val system = ActorSystem("ActorSystem") val hello = system.actorOf(Props[HelloActor].withRouter(RoundRobinRouter(10))) for (i <- 1 to 10) { hello ! HelloActor.SayHello } } 

This is a fairly simple example because it uses a simple round robin router and does not resize. You can do much more with routers, and I highly recommend reading more on them:

http://doc.akka.io/docs/akka/2.2.3/scala/routing.html

+1
source

Source: https://habr.com/ru/post/959059/