繁体   English   中英

我们如何将actor处理的消息的结果发送回实际的发送者

[英]How do we send back the result of processed message by actor to the actual sender

我创建了一个简单的Actor,它从发送方接收消息并处理该消息,并将处理后的结果发送回发送方。

我试图通过Actor模型和发件人达到上述要求

演员代码:

import akka.actor.Actor
import akka.actor.Props

class HelloWorld extends Actor {

  var result:Int =0
  def receive = {

    case dataStr:String =>result =process(dataStr)
    sender ! result

  }

  def process(str:String):Int ={

  str.length +30
 }
 }

ActorApp代码:

import akka.actor.{ActorRef, ActorSystem, Props}

object ActorApp {

  def main(args :Array[String]) ={

    val system = ActorSystem("SimpleActorSystem")
    val actorObj1:ActorRef = system.actorOf(Props[HelloWorld],"helloworld1")
    val res =actorObj1 ! "Hi"
    println(res)

   }

 }

我得到以下输出:

 ()
 [INFO] [10/08/2016 23:21:50.438] [SimpleActorSystem-akka.actor.default-dispatcher-3] [akka://SimpleActorSystem/deadLetters] Message [java.lang.Integer] from Actor[akka://SimpleActorSystem/user/helloworld1#-233096668] to Actor[akka://SimpleActorSystem/deadLetters] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

我期望在主要对象(ActorApp)中输出如下:

 32

如何将处理后的输出发回给发件人? 另外此INFO日志说什么?

考虑一下您在做什么:您正在向HelloWorld演员发送一条消息,在此处进行接收和处理,然后从该演员发送一条消息给发送原始消息的演员(请记住: sender返回ActorRef )。

但是:那是什么演员? HelloWorld演员只有一位。 因此自然不会定义sender (因为您实际上没有从其他参与者发送消息)。 如果您将消息发送给无法传递的接收者,则它们将发送到akkas死信系统Actor[akka://SimpleActorSystem/deadLetters]Actor[akka://SimpleActorSystem/deadLetters] )-这就是日志消息所说的。

那么,您实际上如何返回结果呢? 您使用ask-pattern

导入akka.pattern.ask并使用问号代替感叹号。 现在,您将获得一个可以(希望)通过您的结果解决的未来:

import akka.pattern.ask
import scala.concurrent.duration._

val system = ActorSystem("SimpleActorSystem")
val actorObj1:ActorRef = system.actorOf(Props[HelloWorld],"helloworld1")
val resFuture = (actorObj1 ? "Hi").mapTo[Int]
val res = Await.result(resFuture, 5 seconds)
println(res)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM