我正在寻找一个使用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
发布于 2018-11-08 13:25:02
askWithReplyTo并不意味着将发送参与者self传递到消息中。
askWithReplyTo希望您为它提供一个工厂函数,该函数将得到临时响应参与者的信息,因此,如果您有一条消息,您可以这样构造:
new MyMessage(ActorRef replyTo)
您可以像这样在askWithReplyTo中使用它:
final Future<Object> f = Patterns.askWithReplyTo(
otherActor,
replyTo -> new MyMessage(replyTo),
timeout);第二个参数是lambda,它将使用临时ask调用(当您请求处理响应超时时总是会创建它),这样您就可以将它包含在消息中。
只有当接收方使用该replyTo字段进行响应,而不是使用sender()时,模式才会有用,而这正是您通常要做的响应。
https://stackoverflow.com/questions/53023682
复制相似问题