akka typed actor ask 实例
所属分类 akka
浏览量 662
val serverActor: ActorSystem[EchoMsg] = ActorSystem(ServerActor(), "serverActor")
val resultFuture = serverActor ? (replyTo => EchoMsg(str, replyTo))
val resultFuture = serverActor.ask(EchoMsg(str, _))
replyTo 系统自动创建
Actor[akka://serverActor/temp/user$a#0]
Actor[akka://serverActor/temp/user$b#0]
关键日志信息
server receive msg hello,sender=Actor[akka://serverActor/temp/user$a#0],self=Actor[akka://serverActor/user#0]
EchoMsg(hello,Actor[akka://serverActor/user#0])
server receive msg akka,sender=Actor[akka://serverActor/temp/user$b#0],self=Actor[akka://serverActor/user#0]
EchoMsg(akka,Actor[akka://serverActor/user#0])
server receive msg typed,sender=Actor[akka://serverActor/temp/user$c#0],self=Actor[akka://serverActor/user#0]
EchoMsg(typed,Actor[akka://serverActor/user#0])
/ 根
/system 系统创建
/user 用户创建 ActorSystem.actorOf
/deadLetters
/temp 系统创建 用于实现 ActorRef.ask
/remote 远程引用
/deadLetters 的一个例子见
akka actor ask 模式 实例
完整代码
https://gitee.com/dyyx/hellocode/blob/master/demo/scala/akka/akka-quickstart-scala-maven/src/main/java/com/example/ask/EchoTypedActorAskDemo.scala
package com.example.ask
import akka.actor.typed.scaladsl.AskPattern.Askable
import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.{ActorRef, ActorSystem, Behavior}
import akka.util.Timeout
import java.util.concurrent.TimeUnit
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
final case class EchoMsg(msg: String, sender: ActorRef[EchoMsg])
object ServerActor {
def apply(): Behavior[EchoMsg] = Behaviors.receive { (context, message) =>
println("server receive msg " + message.msg + ",sender=" + message.sender + ",self=" + context.self)
Thread.sleep(500)
message.sender ! EchoMsg(message.msg, context.self)
Behaviors.same
}
}
object EchoTypedActorMain extends App {
val serverActor: ActorSystem[EchoMsg] = ActorSystem(ServerActor(), "serverActor")
val list = List("hello", "akka", "typed", "actor")
implicit private val timeout: Timeout = Timeout(1, TimeUnit.SECONDS)
implicit private val scheduler = serverActor.scheduler
list.foreach { str =>
val resultFuture = serverActor ? (replyTo => EchoMsg(str, replyTo))
resultFuture.onComplete {
case Success(value) => println(value)
}
println()
Thread.sleep(1000)
}
list.foreach { str =>
val resultFuture = serverActor.ask(EchoMsg(str, _))
resultFuture.onComplete {
case Success(value) => println(value)
}
println()
Thread.sleep(1000)
}
}
上一篇
下一篇
scala技术栈新人学习指南
Scala 偏函数 例子1
Scala 偏函数 例子2
scala akka remote 实例
scala akka remote ask 实例
scala future mapTo 用法