[关闭]
@xtccc 2017-01-17T00:31:46.000000Z 字数 2283 阅读 1911

常见问题

给我写信
GitHub

此处输入图片的描述

Akka


目录


1. 获取Akka System的external IP和port


参考:

  1. https://github.com/openbigdatagroup/speedo/blob/master/src/main/scala/com/htc/speedo/akka/AkkaUtil.scala
  2. Akka Remote: get autogenerated port


  1. val systemConfigs =
  2. ConfigFactory.parseString(s""" akka.remote.netty.tcp.hostname = "$localIP" """)
  3. .withFallback(ConfigFactory.parseString(s""" akka.remote.netty.tcp.port = 0 """))
  4. .withFallback(ConfigFactory.load(param.configName))
  5. .resolve()
  6. implicit val system = ActorSystem("systemName", systemConfigs)
  7. // config中:akka.remote.netty.tcp.port = 0
  8. // system运行时真正的external port是什么?



当我们将akka.remote.netty.tcp.port设置为0时,akka system在启动时会随机的选择一个可用端口,那么怎么来知道这个端口号呢?

要获取akka system运行时真正的port(或者称之为external port),需要用到remote information:

  1. class AddressExtension(system: ExtendedActorSystem) extends Extension {
  2. // The address of the akka system (contains remote information)
  3. val address = system.provider.getDefaultAddress
  4. }
  5. object AddressExtension extends ExtensionKey[AddressExtension]
  6. def addressOf(system: ActorSystem): Address = AddressExtension(system).address




2. 怎样寻找一个actor


ActorSelection

参考 When Should I Use Actor Selection?

我们在本地启动一个master actor,它的名字为master,端口为3000,system名为CrossFilterSystem。那么,我在同一个Akka System中的另一个actor内,可以用如下的代码找到该master actor:

  1. private def lookupMaster(address: Address): Unit = {
  2. // import scala.concurrent.ExecutionContext.Implicits.global
  3. implicit val timeout = Timeout(10 seconds)
  4. val f: Future[ActorRef] = context.system.actorSelection(address.toString).resolveOne()
  5. val master: ActorRef = Await.result(f, timeout.duration)
  6. logger.info("找到了Master: " + master.path.toString)
  7. }

运行输出为:

找到了Master: akka.tcp://CrossFilterSystem@127.0.0.1:3000/

可见,通过地址akka.tcp://CrossFilterSystem@127.0.0.1:3000/,可以找到master actor。

但是这个master actor的name为master,并且它应该在/user这个guardian actor下面(/user is the guardian actor for all user-created top-level actors; actors created using ActorSystem.actorOf are found below this one.)。

所以,这个master actor的地址能不能用akka.tcp://CrossFilterSystem@127.0.0.1:3000/user/master来表达呢?我们来试一下。


将以下代码

  1. val f: Future[ActorRef] = context.system.actorSelection(address.toString).resolveOne()

改为

  1. val f: Future[ActorRef] = context.system.actorSelection(RootActorPath(address)/"user"/"master").resolveOne()

运行后输出为:

找到了Master: akka.tcp://CrossFilterSystem@127.0.0.1:3000/user/master



所以,这两个地址应该是等价的,毕竟一个actor必须有自己的独一无二的port。




3. 向远程actor发送消息

参考 What is the name of a remote actor?

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注