akka actor ask 模式 实例
所属分类 akka
浏览量 769
Actor 两种模式 Tell Ask
Tell 完全异步
Ask 返回 future , 可以同步 异步处理
receive 使用 sender() ! msg 发送结果
发送端 使用 ? 运算符 ,获取 future 后 进行 后续处理
import akka.actor.{Actor, ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
import java.util.concurrent.TimeUnit
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
class HelloActor extends Actor {
def receive = {
// case "hello" => println("hello back to you.")
case msg: String => println("msg=" + msg + ",sender=" + sender())
sender() ! msg
case _ => println("what?")
}
}
object Hello extends App {
// actor need an ActorSystem
val system = ActorSystem("HelloSystem")
// create and start the actor
val helloActor = system.actorOf(Props[HelloActor], name = "helloActor")
// send messages
helloActor ! "hello"
implicit val timeout = Timeout(1 ,TimeUnit.SECONDS)
// ask
(helloActor ? "hello") .andThen{
case Success(result) => println("ask result="+result)
case Failure(err) => println((s"ask error: $err"))
}
// 使用 ? 需要 import akka.pattern.ask
// Future[Any]
val future = helloActor ? "hello-ask"
Thread.sleep(100)
println("ask future result = "+future)
Thread.sleep(3000)
// shutdown the actor system
system.terminate()
}
msg=hello,sender=Actor[akka://HelloSystem/deadLetters]
msg=tell hello,sender=Actor[akka://HelloSystem/deadLetters]
msg=hello,sender=Actor[akka://HelloSystem/temp/helloActor$a]
msg=hello-ask,sender=Actor[akka://HelloSystem/temp/helloActor$b]
msg=hello ask2,sender=Actor[akka://HelloSystem/temp/helloActor$c]
发送 tell 消息时 , sender() 获取到 /deadLetters
发送 ask 消息时 , sender() 获取到 /temp/helloActor$xxx
/temp/ 是系统创建的 用于 ask 模式
完整代码
https://gitee.com/dyyx/hellocode/blob/master/demo/scala/akka/akka-quickstart-scala-maven/src/main/java/com/example/dyyx/hello/Hello.scala
上一篇
下一篇
scala那些事
saas财务指标 ARR 与 MRR
shapeless scalaz cats zio
idea debug 技巧
Reactive Programming
sbt 创建运行 Scala play 项目