带配置的 Akka 远程 actor 选择

Akka Remote actor selection with configuration

是否有一种方法可以为远程参与者 选择 设置类似于 Akka docs 中指定的远程参与者 创建 的配置:

akka {
  actor {
    deployment {
      /sampleActor {
        remote = "akka.tcp://sampleActorSystem@127.0.0.1:2553"
      }
    }
  }
}

我不想为此定义自定义变量。

system.actorSelection("sampleActor")

actor选择方法只有两种形式,来自文档:

def actorSelection(path: ActorPath): ActorSelection

Construct an akka.actor.ActorSelection from the given path, which is parsed for wildcards (these are replaced by regular expressions internally). No attempt is made to verify the existence of any part of the supplied path, it is recommended to send a message and gather the replies in order to resolve the matching set of actors.

def actorSelection(path: String): ActorSelection

Construct an akka.actor.ActorSelection from the given path, which is parsed for wildcards (these are replaced by regular expressions internally). No attempt is made to verify the existence of any part of the supplied path, it is recommended to send a message and gather the replies in order to resolve the matching set of actors.

而且 ActorPath 只是从字符串创建的:

def fromString(s: String): ActorPath

Parse string as actor path; throws java.net.MalformedURLException if unable to do so.

所以没有一种直接的方法可以通过在配置中设置一个特定的值来进行演员选择。然而,很容易从配置中提取一个值并将其用于演员选择。给定配置:

akka {
  actor {
    selections: {
      sampleActor: {
        path: "akka.tcp://sampleActorSystem@127.0.0.1:2553/user/sampleActor"
      }
    }
  }
}

您可以使用:

val sampleActorSelection = 
  system.actorSelection(
    system.settings.config.getString("akka.actor.selections.sampleActor.path"))

如果这是您发现自己经常使用的方法,您可以使用隐式 class 向系统添加辅助方法:

implicit class ActorSystemExtension(system: ActorSystem) {

  def actorSelectionFromConfig(actorName: String): ActorSelection {
    system.actorSelection(
        system.settings.config.getString(s"akka.actor.selections.${actorName}.path"))
  }
}