学习 Akka(二):第一个 Akka 应用

依赖

libraryDependencies ++= Seq(  
  "com.typesafe.akka" %% "akka-actor" % "2.4.8",
  "org.scala-lang.modules" %% "scala-java8-compat" % "0.7.0",
  "com.typesafe.akka" %% "akka-testkit" % "2.4.8" % "test",
  "org.scalatest" %% "scalatest" % "3.0.0" % "test"
)

Actor

class PongActor extends Actor {  
  val logger = Logging(context.system, this)

  override def receive: Receive = {
    case "Ping" => {
      logger.info("Ping")
      sender() ! "Pong"
    }
    case _ => sender() ! Status.Failure(new Exception("Unkown Message"))
  }

}

测试

import akka.pattern.ask  
import scala.concurrent.duration._  
implicit val system = ActorSystem.create()  
implicit val timeout = Timeout(5 seconds)  
val actorRef = system.actorOf(Props(classOf[PongActor]))  
val future = actorRef ? "Ping"  
val result = Await.result(future.mapTo[String], 1 second)  
assert(result == "Pong")