Akka¶
Actors have:
- A mailbox (the queue where messages end up).
- A behavior (the state of the actor, internal variables etc.).
- Messages (pieces of data representing a signal, similar to method calls and their parameters).
- An execution environment (the machinery that takes actors that have messages to react to and invokes their message handling code).
- An address.
sbt:
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor" % "2.5.6",
"com.typesafe.akka" %% "akka-testkit" % "2.5.6" % Test
)
Basic Example¶
//#full-example
package com.lightbend.akka.sample
import akka.actor.{ Actor, ActorLogging, ActorRef, ActorSystem, Props }
import scala.io.StdIn
//#greeter-companion
//#greeter-messages
object Greeter {
//#greeter-messages
def props(message: String, printerActor: ActorRef): Props = Props(new Greeter(message, printerActor))
//#greeter-messages
final case class WhoToGreet(who: String)
case object Greet
}
//#greeter-messages
//#greeter-companion
//#greeter-actor
class Greeter(message: String, printerActor: ActorRef) extends Actor {
import Greeter._
import Printer._
var greeting = ""
def receive = {
case WhoToGreet(who) =>
greeting = s"$message, $who"
case Greet =>
//#greeter-send-message
printerActor ! Greeting(greeting)
//#greeter-send-message
}
}
//#greeter-actor
//#printer-companion
//#printer-messages
object Printer {
//#printer-messages
def props: Props = Props[Printer]
//#printer-messages
final case class Greeting(greeting: String)
}
//#printer-messages
//#printer-companion
//#printer-actor
class Printer extends Actor with ActorLogging {
import Printer._
def receive = {
case Greeting(greeting) =>
log.info(s"Greeting received (from ${sender()}): $greeting")
}
}
//#printer-actor
//#main-class
object AkkaQuickstart extends App {
import Greeter._
// Create the 'helloAkka' actor system
val system: ActorSystem = ActorSystem("helloAkka")
try {
//#create-actors
// Create the printer actor
val printer: ActorRef = system.actorOf(Printer.props, "printerActor")
// Create the 'greeter' actors
val howdyGreeter: ActorRef =
system.actorOf(Greeter.props("Howdy", printer), "howdyGreeter")
val helloGreeter: ActorRef =
system.actorOf(Greeter.props("Hello", printer), "helloGreeter")
val goodDayGreeter: ActorRef =
system.actorOf(Greeter.props("Good day", printer), "goodDayGreeter")
//#create-actors
//#main-send-messages
howdyGreeter ! WhoToGreet("Akka")
howdyGreeter ! Greet
howdyGreeter ! WhoToGreet("Lightbend")
howdyGreeter ! Greet
helloGreeter ! WhoToGreet("Scala")
helloGreeter ! Greet
goodDayGreeter ! WhoToGreet("Play")
goodDayGreeter ! Greet
//#main-send-messages
println(">>> Press ENTER to exit <<<")
StdIn.readLine()
} finally {
system.terminate()
}
}
//#main-class
//#full-example