通过Akka以编程方式获取临时端口 [英] Programmatically obtain ephemeral port with Akka

查看:87
本文介绍了通过Akka以编程方式获取临时端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Akka中将ActorSystem配置为使用临时tcp端口(更具体地说,我将http端口配置为0),那么一旦ActorSystem启动,是否可以通过编程方式获取此端口?

If I configure an ActorSystem in Akka to use an emphemeral tcp port (more specifically, I configure the http port to 0), is there a way to programmatically obtain this port once the ActorSystem is started?

任何尝试使用actorOf创建一个actor,然后打印出actor路径的操作都会显示一个本地引用的actor。另外,我尝试在事件流上注册RemoteLifeCycleEvent侦听器,但这只能在服务器启动后才能完成,因此会错过RemoteServerStarted事件。

Any attempts to create an actor using actorOf, and then printing out the actor path shows a locally-referenced actor. Additionally, I tried registering a RemoteLifeCycleEvent listener on the event stream, but this can only be done after the server has been started, and hence misses RemoteServerStarted event.

推荐答案

在这里:

class MyExtensionImpl(system: ExtendedActorSystem) extends Extension {
  def address = system.provider match {
    case rarp: RemoteActorRefProvider => rarp.transport.address
    case _ => system.provider.rootPath.address
  }
}

object MyExtension extends ExtensionKey[MyExtensionImpl]

val address = MyExtension(system).address
val port = address.port.getOrElse(sys.error("not a remote actor system"))

(请注意,此代码适用于Akka2.0.x。在2.1.x中,您可以使用 system.provider避免通过 RemoteActorRefProvider 进行操作。 getDefaultAddress

(note this code works with Akka 2.0.x. In 2.1.x you can avoid going through RemoteActorRefProvider by using system.provider.getDefaultAddress)

这篇关于通过Akka以编程方式获取临时端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆