我不明白关于在回调中关闭 actor ref 的声明。 目前我正在使用
public void onReceive(Object message) throws Exception {
ActorRef senderActorRef = getSender(); //never close over a future
if (message instanceof String) {
Future<String> f =akka.dispatch.Futures.future(new Callable<String>() {
public String call() {
String value= jedisWrapper.getString("name");
senderActorRef.tell((String) message,ActorRef.noSender());
return "what";
}
}, ex);
f.onSuccess(new OnSuccessExtension(), ex);
}
}
private final class OnSuccessExtension extends OnSuccess {
@Override
public void onSuccess(Object arg0) throws Throwable {
log.info("what");
}
}
这是正确的使用方法吗? 如何在 OnSuccess 方法中传递 Sender Actor 引用? 另外 onSuccess 和 OnComplete 之间有什么区别? 如果我想使用 onComplete 我该如何使用它?
答案:在构造函数中传递 Sender Actor Ref。另一位网友给出的答案。 OnSuccess 是 OnComplete 的一种特殊形式。 Akka 文档中的 OnComplete 用法
final ExecutionContext ec = system.dispatcher();
future.onComplete(new OnComplete<String>() {
public void onComplete(Throwable failure, String result) {
if (failure != null) {
//We got a failure, handle it here
} else {
// We got a result, do something with it
}
}
}, ec);
最佳答案
将其传递到构造函数中:
public void onReceive(Object message) throws Exception {
final ActorRef senderActorRef = getSender(); //never close over a future
if (message instanceof String) {
Future<String> f = // ...
f.onSuccess(new OnSuccessExtension(senderActorRef), ex);
}
}
private final class OnSuccessExtension extends OnSuccess {
private final ActorRef senderActorRef;
public OnSuccessExtension(ActorRef senderActorRef) {
this.senderActorRef = senderActorRef;
}
@Override
public void onSuccess(Object arg0) throws Throwable {
log.info("what");
// use senderActorRef
}
}
关于java - Akka java 永远不会关闭 ActorRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32848205/