如何打印akka系统中的所有演员?

时间:2014-09-16 04:55:33

标签: scala debugging akka

我创建了akka系统。假设其中有一些演员。我如何用他们的路径打印akka系统中的所有演员? (用于调试目的)

3 个答案:

答案 0 :(得分:14)

This reply by Roland Kuhn表明这不是一个完全无关紧要的问题,但您可以使用Identify-ActorIdentity请求 - 响应协议非常接近(对于将在合理时间内回复消息的演员)所有演员都服从。

将一些未经测试的代码拼凑在一起以说明这个想法:

import akka.actor._

def receive = {
    case 'listActors =>
      context.actorSelection("/user/*") ! Identify()

    case path: ActorPath =>
      context.actorSelection(path / "*") ! Identify()

    case ActorIdentity(_, Some(ref)) =>
      log.info("Got actor " + ref.path.toString)
      self ! ref.path
}

答案 1 :(得分:8)

ActorSystem具有私有方法printTree,您可以将其用于调试。

1)私人方法来电者(来自https://gist.github.com/jorgeortiz85/908035):

class PrivateMethodCaller(x: AnyRef, methodName: String) {
  def apply(_args: Any*): Any = {
    val args = _args.map(_.asInstanceOf[AnyRef])

    def _parents: Stream[Class[_]] = Stream(x.getClass) #::: _parents.map(_.getSuperclass)

    val parents = _parents.takeWhile(_ != null).toList
    val methods = parents.flatMap(_.getDeclaredMethods)
    val method = methods.find(_.getName == methodName).getOrElse(throw new IllegalArgumentException("Method " + methodName + " not found"))
    method.setAccessible(true)
    method.invoke(x, args: _*)
  }
}

class PrivateMethodExposer(x: AnyRef) {
  def apply(method: scala.Symbol): PrivateMethodCaller = new PrivateMethodCaller(x, method.name)
}

2)用法

val res = new PrivateMethodExposer(system)('printTree)()
println(res)

将打印:

-> / LocalActorRefProvider$$anon$1 class akka.actor.LocalActorRefProvider$Guardian status=0 2 children
   ⌊-> system LocalActorRef class akka.actor.LocalActorRefProvider$SystemGuardian status=0 3 children
   |   ⌊-> deadLetterListener RepointableActorRef class akka.event.DeadLetterListener status=0 no children
   |   ⌊-> eventStreamUnsubscriber-1 RepointableActorRef class akka.event.EventStreamUnsubscriber status=0 no children
   |   ⌊-> log1-Logging$DefaultLogger RepointableActorRef class akka.event.Logging$DefaultLogger status=0 no children
   ⌊-> user LocalActorRef class akka.actor.LocalActorRefProvider$Guardian status=0 1 children
...

要注意,它可能导致OOM如果你有很多演员。

答案 2 :(得分:2)

根据the documentation,您可以将ActorSelection与通配符*一起使用,以使演员发送识别消息。你可以让一个演员收集ActorRef

如@ chris-martin所述,只有当前不忙的演员才会发送。一个非常简单的演员:

// make all the available actor to send an identifying message
public void freeActors()
{
  ActorSelection selection =
    getContext().actorSelection("/user/*");
  selection.tell(new Identify(identifyId), getSelf());
}

...
// collect responses
@Override
public void onReceive(Object message) {
  if (message instanceof ActorIdentity) {
    ActorIdentity identity = (ActorIdentity) message;
    // get the ref of the sender 
    ActorRef ref = identity.getRef();
    // the sender is up and available
   ...
编辑:我知道这是针对Java的,但它似乎对我很有帮助。