4

我正在学习 akka-remote,我做的一件事LocalActorSystem是获取远程演员参考并向他发送消息

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

我的Remote样子

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,如果它死了,LocalActorSystem 就知道了。所以我做了

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

但随后编译器失败并显示以下消息

在此处输入图像描述

问题

  1. ActorSelection既然不是,我怎么能发送消息Actor
  2. 如何观看 RemoteActor?

更新
但是,不推荐使用的 API 不会抱怨

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

1 回答 1

8

当您通过 进行查找时actorSelection,您返回的对象类型是 anActorSelection而不是ActorRef. 现在, anActorSelection确实支持两者tell (!)ask (?)因此您可以像使用ActorRef. 但是查找演员 viaactorSelection支持通配符的概念,因此ActorSelection您返回的可能代表多个演员,并允许您向多个演员发送消息。例如,如果您这样做:

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

这将为您提供绑定到该名称ActorSelection的父级下的所有子级。如果有两个孩子并且您通过 that 发送消息,则该消息将传递给两个孩子。ActorReffooActorSelection

在您的情况下,看起来您正在查找单个演员实例。在这种情况下,您可以通过调用它来获取ActorRef您的信息。这将返回一个,完成后将为您提供一个您可以远程观看的内容。您还可以发送一条消息并等待包含要观看的 ref 的响应。ActorSelectionresolveOneFuture[ActorRef]ActorRefActorSelectionIdentifyActorIdentity

您应该在此处查看文档,特别是该Identifying Actors via Actor Selection部分。

于 2015-06-24T00:11:43.360 回答