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!