2

我有一个 Java 客户端,它获取一个自动生成的端口。启动actor系统后,我想访问端口。

Config clientConfig = ConfigFactory.parseString("akka.remote.netty.tcp.port = 0")
        .withFallback(ConfigFactory.parseString("akka.remote.netty.tcp.hostname = " + serverHostName))
        .withFallback(ConfigFactory.load("common"));

actorSystem = ActorSystem.create("clientActorSystem", clientConfig);

// how to access the generated port here..!?

端口必须已经设置,因为之后的日志输出ActorSystem.create(...)是这样的:

[INFO] [03/31/2016 14:11:32.042] [main] [akka.remote.Remoting] Starting remoting
[INFO] [03/31/2016 14:11:32.233] [main] [akka.remote.Remoting] Remoting started; listening on addresses :[akka.tcp://actorSystem@localhost:58735]
[INFO] [03/31/2016 14:11:32.234] [main] [akka.remote.Remoting] Remoting now listens on addresses: [akka.tcp://actorSystem@localhost:58735]

如果我尝试通过配置来获取它actorSystem.settings().config().getValue("akka.remote.netty.tcp.port"),我仍然会得到之前定义的 0。

有谁知道如何访问此端口(示例中为 58735)?

4

2 回答 2

1

使用 scala,您可以获得当前运行 Actor 系统的端口选项:

val port = system.provider.getDefaultAddress.port

希望您能够在 Java 中获得相同的代码。

于 2016-04-03T20:06:56.307 回答
0

接受的答案可能适用于旧版本的 Akka,但截至目前(2.5.x 版),您将得到如下信息:

错误:(22, 18) trait ActorRefFactory 中的方法提供程序无法在 akka.actor.ActorSystem 中访问

解决方案是使用akka extensions。这是我的使用方法:

例子。斯卡拉

package example

import akka.actor._

class AddressExtension(system: ExtendedActorSystem) extends Extension {
  val address: Address = system.provider.getDefaultAddress
}

object AddressExtension extends ExtensionId[AddressExtension] {
  def createExtension(system: ExtendedActorSystem): AddressExtension = new AddressExtension(system)

  def hostOf(system: ActorSystem): String = AddressExtension(system).address.host.getOrElse("")
  def portOf(system: ActorSystem): Int    = AddressExtension(system).address.port.getOrElse(0)
}

object Main extends App {
  val system = ActorSystem("Main")
  println(AddressExtension.portOf(system))
}
于 2018-06-13T14:49:59.093 回答