我有三个远程Akka演员: 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;
}
我刚刚检查了一下,ActorRef
是Serializable
,所以从理论上讲,我上面提出的解决方案应该有效,但是是否有一种不同的/官方/更干净的方法来做到这一点呢?
发布于 2014-02-17 15:05:31
您的解决方案看起来很好,而且是一件常见的事情。Akka引用设计为位置透明和可串行化。因此,您可以将Actor引用发送到远程客户端,他们只需使用它们,而无需任何其他设置。
发布于 2014-02-17 15:28:53
如果参与者C只需要有对参与者A的引用,则只需使用tell方法将actor B中的行更改为:
refC.tell(refA, getSender());
如果演员C必须同时引用actor A和Actor B,那么您可以做两件事:
1)使用您提供的代码。
2)使用Actor C中的getContext().actorSelection("actor_name")方法来获取Actor A。如何在Akka文件中描述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 ...){}
}
}
https://stackoverflow.com/questions/21832131
复制相似问题