【问题标题】:Akka in Scala, exclamation mark and question markScala中的Akka,感叹号和问号
【发布时间】:2013-07-12 17:30:00
【问题描述】:

在向 Actor 发送消息时,感叹号 (!) 和问号 (?) 有什么区别?

myActor ! Hello(value1)
myActor ? Hello(value1)

【问题讨论】:

    标签: scala operators akka actor


    【解决方案1】:

    从收件人的角度来看,它看到tellask 消息的方式相同。但是,当接收到tell 时,sender 的值将是发送消息的参与者的引用,而对于asksender 的设置使得任何回复都转到创建的Future在提出问题的演员中。

    ask 有一个优势,即很容易知道您收到的响应肯定是您询问的消息的结果,而使用 Tell,您可能需要使用唯一 ID 来实现类似的结果。但是对于ask,您需要设置timeout,之后如果没有收到响应,Future 将失败。

    在下面的代码中,tellask 实现了相同的效果。

    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!"
      }
    }
    

    【讨论】:

      【解决方案2】:

      无耻复制[awesome]official doc(查看发送消息部分了解更多信息):

      消息通过以下方法之一发送给 Actor。

      ! 表示“即发即弃”,例如异步发送消息和 立即返回。也称为tell

      ? 发送消息 异步并返回一个Future 表示可能的回复。 也称为ask

      【讨论】:

      猜你喜欢
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      相关资源
      最近更新 更多