我正在寻找一个如何使用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
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]
答案 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()
来响应时,此模式才有用。