如何在Akka Java中使用Patterns.askWithReplyTo

时间:2018-10-27 15:52:34

标签: java akka akka-cluster

我正在寻找一个如何使用Java使用Akka的模式Patterns.askWithReplyTo的示例。

Github提供了一个示例项目:https://github.com/pcdhan/akka-patterns.git

我的挑战是我无法在有效负载中包含发送方的ActorRef。

本地演员

ActorRef localA= system.actorOf(LocalActor.props(), "localA");

远程演员

Timeout timeout = new Timeout(10000, TimeUnit.MILLISECONDS);
ActorSelection actorSelection=system.actorSelection("akka.tcp://ClusterSystem@localhost:2551/user/ActorA");
Future<Object> future = Patterns.ask(actorSelection, new Identify(""), timeout);
ActorIdentity reply = (ActorIdentity) Await.result(future, timeout.duration());
ActorRef actorRef = reply.ref().get(); //my remote actor ref

将有效负载与ActorRef(localA)一起发送到远程Actor

Payload payload = new Payload(); //How do I pass localA here
payload.setMsg("0");
Future<Object> askWithSenderRef = 
Patterns.askWithReplyTo(actorRef,payload,20000L);
Payload responsePayload = (Payload) Await.result(askWithSenderRef, 
timeout.duration());
System.out.println("Response from Remote Actor Payload: "+responsePayload.getMsg());

有效载荷

public class Payload implements Function<ActorRef, Object>, Serializable {
private static final long serialVersionUID = 1L;

String msg;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

@Override
public Object apply(ActorRef param) throws Exception {
    return this;
}

}

远程演员日志

...Actor[akka.tcp://ClusterSystem@localhost:53324/temp/$d]
...Actor[akka.tcp://ClusterSystem@localhost:53324/temp/$e]

我希望... / user / localA,但是我得到了/ temp / $ d

1 个答案:

答案 0 :(得分:1)

askWithReplyTo并不意味着将发送方self传递到消息中。

askWithReplyTo希望您为其提供一个工厂函数,该函数将被馈给临时响应参与者,因此,如果您有一条消息可以构造如下:

new MyMessage(ActorRef replyTo)

您可以将其与askWithReplyTo一起使用,

final Future<Object> f = Patterns.askWithReplyTo(
  otherActor,
  replyTo -> new MyMessage(replyTo),
  timeout);

第二个参数是一个lambda值,它将通过临时Ask-actor调用(总是在您确实要求处理响应超时时创建),以便可以将其包括在消息中。

仅当接收方使用该replyTo字段而不是通常用于响应的sender()来响应时,此模式才有用。