加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:05:45 所属栏目:安全 来源:网络整理
导读:我正在学习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 de
我正在学习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选择识别演员.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读