Akka java永远不会关闭ActorRef

时间:2015-09-29 15:37:05

标签: java akka future

我不理解关于在回调中关闭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 ref? 还有什么是onSuccess和OnComplete之间的区别? 如果我想使用onComplete,我将如何使用它?

答案:在构造函数中传递Sender Actor Ref。另一个用户给出的答案。 OnSuccess是OnComplete的一种特殊形式。 来自Akka docs的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);

1 个答案:

答案 0 :(得分:1)

在构造函数中传递它:

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
    }
}