Akka hello world(Scala)
- 添加 akka-actor 依赖项(SBT 示例)
libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.4.8"
- 创建 actor 类:
字符串输出的 Actor:
class OutputActor extends Actor {
override def receive: Receive = {
case message => println(message)
}
}
字符串修改的 Actor:
class AppendActor(outputActor: ActorRef) extends Actor {
override def receive: Receive = {
case message: String =>
val changed = s"Hello, $message!"
outputActor ! changed
case unknown =>
println(s"unknown message: $unknown")
}
}
- 创建 actor 系统并发送消息
object HelloWorld extends App {
val system = ActorSystem("HelloWorld")
val outputActor = system.actorOf(Props[OutputActor], name = "output")
val appendActor = system.actorOf(Props(classOf[AppendActor], outputActor), name = "appender")
appendActor ! "Akka" // send test message
Thread.sleep(500) // wait for async evaluation
system.terminate() // terminate actors system
}
程序输出:
Hello, Akka!