如何观察远程Akka Actor?

4

我正在学习 akka-remote,其中一个任务是在我的 LocalActorSystem 中获取远程 actor 引用并向其发送消息。

class LocalActor extends Actor {
  val remote = context.actorSelection("akka.tcp://HelloRemoteSystem@127.0.0.1:5150/user/RemoteActor")
  var counter = 0

  def receive = {
    case "START" =>
      remote ! "Hello from the LocalActor"
    case msg: String =>
      println(s"LocalActor received message: '$msg'")
      if (counter < 5) {
        sender ! "Hello back to you"
        counter += 1
      }
  }
}

我的 远程 看起来像

object Remote extends App {
  val system = ActorSystem("HelloRemoteSystem", ConfigFactory.load("remote"))
  val remoteActor = system.actorOf(Props[RemoteActor], name = "RemoteActor")
  remoteActor ! "The RemoteActor is alive"
}

class RemoteActor extends Actor {
  def receive = {
    case msg: String =>
      println(s"RemoteActor received message '$msg'")
      sender ! "Hello from the RemoteActor"
  }
}

我还希望能够观察remoteActor,以便在其停止工作时,本地ActorSystem能够得知。因此,我执行了以下操作:

  val remote = context.actorSelection("akka.tcp://HelloRemoteSystem@127.0.0.1:5150/user/RemoteActor")
  context watch remote

但是编译器报以下错误信息:

enter image description here

问题

  1. 既然ActorSelection不是Actor,我怎么能够发送消息给它呢?
  2. 如何监视远程RemoteActor

更新
然而,弃用的API没有抱怨。

val remote = context.actorFor("akka.tcp://HelloRemoteSystem@127.0.0.1:5150/user/RemoteActor")
  context watch remote
1个回答

8
当您通过actorSelection进行查找时,您获得的对象类型是ActorSelection而不是ActorRef。现在,ActorSelection支持tell(!)ask(?),因此您可以像处理ActorRef一样与其交互。但是,通过actorSelection查找演员支持通配符的概念,因此您获得的ActorSelection可能代表多个演员,并允许您向多个演员发送消息。例如,如果您执行以下操作:

system.actorSelection("/user/foo/*")

这将为您提供一个ActorSelection,用于父ActorRef下绑定名称foo的所有子级。如果有两个子级并且通过该ActorSelection发送消息,则该消息将传递给两个子级。
在您的情况下,看起来您正在查找单个actor实例。在这种情况下,您可以通过在其上调用resolveOne来从您的ActorSelection获取ActorRef。这将返回一个Future[ActorRef],当完成时将为您提供一个ActorRef,您可以远程监视它。您还可以向ActorSelection发送Identify消息,并等待包含要观察的ref的ActorIdentity响应。
您应该查看文档here,特别是通过Actor Selection识别Actor部分。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接