Programmatically get an ephemeral port with Akka

If I configure ActorSystem in Akka to use the emphemeral tcp port (more precisely, I will set the http port to 0), is there a way to programmatically get this port after starting ActorSystem?

Any attempts to create an actor using actorOf and then print the path to the actor show the actor referenced by the local link. In addition, I tried to register the RemoteLifeCycleEvent listener in the event stream, but this can only be done after the server starts and, therefore, misses the RemoteServerStarted event.

+3
source share
1 answer

Here you go:

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"))

( , Akka 2.0.x. 2.1.x RemoteActorRefProvider system.provider.getDefaultAddress)

+3

All Articles