Scala 中的 Akka,感叹号和问号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17644273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Akka in Scala, exclamation mark and question mark
提问by ticofab
What is the difference between exclamation mark (!) and question mark (?) when sending messages to Actors?
向 Actors 发送消息时,感叹号 ( !) 和问号 ( ?) 有什么区别?
myActor ! Hello(value1)
myActor ? Hello(value1)
回答by om-nom-nom
Shamelessly copied [awesome]official doc(look Send messagessection for more):
无耻地复制了[awesome]官方文档(查看发送消息部分了解更多信息):
Messages are sent to an Actor through one of the following methods.
!means “fire-and-forget”, e.g. send a message asynchronously and return immediately. Also known astell.
?sends a message asynchronously and returns aFuturerepresenting a possible reply. Also known asask.
消息通过以下方法之一发送到 Actor。
!表示“即发即忘”,例如异步发送消息并立即返回。也称为tell。
?异步发送消息并返回一个Future代表可能的回复。也称为ask。
回答by mattinbits
From the recipient's point of view, it sees telland askmessages the same way. However when receiving a tellthe value of senderwill be the reference of the actor who sent the message, whereas for an ask, the senderis set up such that any reply goes to the Futurecreated in the actor who did the asking.
从收件人的角度来看,它以相同的方式查看tell和ask发送消息。然而,当接收到 a 时,tell的值sender将是发送消息的参与者的引用,而对于 a ask,sender则设置为使得任何回复都发送到Future执行询问的参与者中创建的对象。
There is an advantage in ask, that it is easy to know that the response you're receiving was definitely a result of the message you asked, whereas with Tell, you may need to use unique IDs to achieve a similar result. However with askyou need to set a timeoutafter which the Futurewill fail if no response is received.
有一个优点ask,很容易知道您收到的响应肯定是您询问的消息的结果,而使用 Tell,您可能需要使用唯一 ID 来实现类似的结果。但是,ask您需要设置一个,timeout之后Future如果没有收到响应,则将失败。
In the code below, the same effect is achieved with a telland and ask.
在下面的代码中,使用telland实现了相同的效果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!"
}
}

