java - Akka java 永远不会关闭 ActorRef

标签 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 引用? 另外 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/

相关文章:

scala - 在做 Future.sequence 时如何知道哪个 Future 失败?

scala - 必须显式运行 akka 多 jvm 测试

scala - 玩框架和 scala Future(s) 链。让它更漂亮

c++ - 是什么给了 std::future 一些共享状态

java - 为什么我的 android 应用程序这么慢?

java - 方法内部的局部内部类的数量是否有限制?

java - Spring MVC + Hibernate : No Hibernate Session bound to thread, 并且配置不允许在此处创建非事务性的

java - 调理使用哪种方法

Scala:Akka actor 不会死在 Play Framework 2.2.0 中

java - Future.cancel 和 ReentrantLocks