【问题标题】:How to pass remote references between Akka actors?如何在 Akka 演员之间传递远程引用?
【发布时间】:2014-03-16 22:17:56
【问题描述】:

我有三个远程 Akka Actor:A、B 和 C。A 向 B 发送消息,B 保存 A 的引用(见下文)。另外,我需要 B 将 A 的引用发送给 C。我该怎么做? B 的 Java 代码如下所示:

public class B extends UntypedActor {
    //---------------------------------------------------------------
    /**
     * {@inheritDoc}
     */
    @Override
    public void onReceive(Object object) throws Exception {
        if (refA == null) {
            refA = getSender();
        }

        // how do I send refA to C???
        refC.tell(refA, getSelf()); // <== like this?
    }

    // set during onReceive
    private ActorRef refA = null;

    // initialized in constructor
    private final ActorRef refC;
}

我刚刚检查了一下,ActorRefSerializable 所以理论上我上面提出的解决方案应该可以工作,但是有没有不同的/官方的/更清洁的方法呢?

【问题讨论】:

    标签: java scala akka


    【解决方案1】:

    您的解决方案看起来不错,而且很常见。 Akka 引用设计为位置透明和可序列化。因此,您可以将 Actor 引用发送到远程客户端,他们无需任何额外设置即可使用它们。

    【讨论】:

      【解决方案2】:

      如果actor C 只需要对actor A 的引用,则只需将actor B 中的行用tell 方法更改为:

      refC.tell(refA, getSender()); 
      

      如果演员 C 必须同时引用演员 A 和演员 B,那么您可以做两件事:

      1) 使用您提供的代码。

      2) 在 Actor C 中使用方法 getContext().actorSelection("actor_name") 来获取 Actor A。Akka Documentation 中描述了 actorSelection 的工作原理,但它看起来像如下:

      public class ActorC extends UntypedActor {
          private static String ID="whateverID";
          private ActorRef actorA;
          {
            getContext().actorSelection("akka.tcp://app@host:port/user/actorAName").
            tell(new Identify(ID), getSelf());
          }
          //As an alternative, if you need the ActorA initialized in the constructor,
          //you can use the .resolveOne method.
          //public ActorC(){
          //    super();
          //    Timeout timeout=new Timeout(4, TimeUnit.SECONDS);
          //      try {
          //          httpProducer=Await.result(getContext().actorSelection("akka.tcp://app@host:port/user/actorAName").resolveOne(timeout), timeout.duration());
          //      } catch (Exception e) {
          //      Logger.error("Error fetching the routerHTTProducer");
          //      }
          //}
          @Override
          public void onReceive(Object m) throws Exception {
              if (m instanceof ActorIdentity) {
                  ActorIdentity identity = (ActorIdentity) m;
                  if (identity.correlationId().equals(ID) && identity.getRef() != null) {
                      actorA= identity.getRef();
                  }           
              }
              //else if (m instanceof ...){}  
          }
      }    
      

      【讨论】:

        猜你喜欢
        • 2014-05-28
        • 1970-01-01
        • 2012-05-09
        • 2015-10-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 2016-01-20
        • 2013-07-20
        相关资源
        最近更新 更多