斯卡拉 – 如何看远程Akka演员?

前端之家收集整理的这篇文章主要介绍了斯卡拉 – 如何看远程Akka演员?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习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,这样如果死了,LocalActorSystem就知道了.所以我做了

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

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

>为什么我能够向ActorSelection发送消息,因为它不是Actor?
>我如何观看RemoteActor?

更新
但是,弃用的API不会抱怨

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

解决方法

当您通过actorSelection进行查找时,您获得的那种类型的对象是ActorSelection而不是ActorRef.现在,ActorSelection确实支持tell(!)和ask(?),因此您可以像使用ActorRef一样与它进行交互.但是通过actorSelection查找的actor支持通配符的概念,因此您返回的ActorSelection可能代表多个actor,并允许您向多个actor发送消息.例如,如果您这样做:

system.actorSelection( “/用户/富/ *”)

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

在您的情况下,看起来您正在查找单个actor实例.在这种情况下,您可以通过调用resolveOne从ActorSelection获取ActorRef.这将返回Future [ActorRef],完成后将为您提供可以远程观看的ActorRef.您还可以向ActorSelection发送Identify消息,并等待包含要观看的ref的ActorIdentity响应.

您应该查看文档here,特别是通过Actor Selection选择识别演员.

猜你在找的Scala相关文章