We will create the following two actors here:
- QueryActor: Sends a message to RandomNumberGenerator to generate a random number
- RandomNumberGeneratorActor: Sends the generated random number to the QueryActor
The following are the steps for creating the actors:
- Create a Scala file, Communication.scala, in the package com.packt.chapter1.
- Create an object, Messages, which will contain the messages to be sent to the actors for communicating with each other.
- Add import to the top of the file:
import akka.actor.ActorRef
After adding the import add the code that follows:
object Messages {
case class Done(randomNumber: Int)
case object GiveMeRandomNumber
case class Start(actorRef: ActorRef)
}
- Define RandomNumberGeneratorActor, which generates a random number and sends it back to the sender.
- Add the two imports given next to the top of the file:
import akka.actor.Actor
import scala.util.Random._
Now add the code that follows:
class RandomNumberGeneratorActor extends Actor {
import Messages._
override def receive: Receive = {
case GiveMeRandomNumber =>
println("received a message to
generate a random integer")
val randomNumber = nextInt
sender ! Done(randomNumber)
}
}
- Create a queryActor, which sends messages to RandomNumberGeneratorActor and receives the random number:
class QueryActor extends Actor {
import Messages._
override def receive: Receive = {
case Start(actorRef) => println(s"send me the next
random number")
actorRef ! GiveMeRandomNumber
case Done(randomNumber) =>
println(s"received a random number $randomNumber")
}
}
- Create an application object, Communication, to see the output:
object Communication extends App {
import Messages._
val actorSystem = ActorSystem("HelloAkka")
val randomNumberGenerator =
actorSystem.actorOf(Props[RandomNumberGeneratorActor],
"randomNumberGeneratorActor")
val queryActor = actorSystem.actorOf(Props[QueryActor],
"queryActor")
queryActor ! Start(randomNumberGenerator)
}
- Now run the application in the IDE or from the console, and the output will be displayed as follows:
send me the next random number
received a message to generate a random integer
received a random number 841431704