akka Akka Hello World(Scala)
示例
添加akka-actor依赖关系(SBT示例)
libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.4.8"
创建演员类:
字符串输出的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")
}
}
创建角色系统并发送消息
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" // 发送测试信息
Thread.sleep(500) // 等待异步评估
system.terminate() // 终止演员系统
}
程序输出:
哈kka,阿卡!
以上是 akka Akka Hello World(Scala) 的全部内容, 来源链接: utcz.com/z/315824.html