向Actor发送消息时,感叹号(!
)和问号(?
)有什么区别?
myActor ! Hello(value1)
myActor ? Hello(value1)
Answers:
从收件人的角度来看,它以相同的方式查看tell
和ask
发送消息。但是,当接收到时,tell
的值sender
将是发送消息的演员的引用,而对于ask
,则将sender
设置为,使得任何答复都将发送给Future
进行询问的演员中的创建者。
中的一个优点是ask
,您很容易知道收到的响应肯定是您询问的消息的结果,而使用Tell可能需要使用唯一的ID来获得类似的结果。但是,ask
您需要设置a,timeout
之后Future
如果未收到响应,它将失败。
在下面的代码中,使用tell
和和可实现相同的效果ask
。
import akka.actor.{Props, Actor}
import scala.concurrent.duration._
import akka.pattern.ask
class TellActor extends Actor {
val recipient = context.actorOf(Props[ReceiveActor])
def receive = {
case "Start" =>
recipient ! "Hello" // equivalent to recipient.tell("hello", self)
case reply => println(reply)
}
}
class AskActor extends Actor {
val recipient = context.actorOf(Props[ReceiveActor])
def receive = {
case "Start" =>
implicit val timeout = 3 seconds
val replyF = recipient ? "Hello" // equivalent to recipient.ask("Hello")
replyF.onSuccess{
case reply => println(reply)
}
}
}
class ReceiveActor extends Actor {
def receive = {
case "Hello" => sender ! "And Hello to you!"
}
}