如何在Java中异步使用Akka Futures [英] How to using Akka Futures asynchronously in Java

查看:109
本文介绍了如何在Java中异步使用Akka Futures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在如下所示的Java服务层中进行呼叫;

I'm making a call in a Java service layer that looks like this;

Future<Object> future = Patterns.ask(myActor, message, timeout);

Response res = (Response) Await.result(future, timeout.duration());

我已经阅读了Akka文档,意识到不建议这样做。我需要将响应对象返回给调用方法。是否可以通过Java服务与Akka异步执行此操作?我尝试使用 future.onSuccess 方法执行此操作,但是 onSuccess 方法不允许返回值,因此我可以不返回值。

I've read the Akka documentation and realize blocking like this is not recommended. I need to return the response object to the calling method. Is it possible do this asynchronously with Akka from my Java service? I tried to do this using the future.onSuccess method however the onSuccess method does not allow a return value so I can't return the value.

推荐答案

在线程之间传递数据的一种akka方法,实际上,您通过在上面进行阻塞来执行的操作是编写期货或向演员发送消息。

The akka way of passing data between threads, which is essentially what you are doing by blocking above is to compose futures or to send a message to an Actor.

以下示例摘自 Akka文档

final ExecutionContext ec = system.dispatcher();

Future<String> f1 = future(new Callable<String>() {
    public String call() {
        return "Hello" + "World";
    }
}, ec);

Future<Integer> f2 = f1.map(new Mapper<String, Integer>() {
    public Integer apply(String s) {
        return s.length();
    }
}, ec);

f2.onSuccess(new PrintResult<Integer>(), system.dispatcher());

请注意,在此示例中,数据正在返回,或更确切地说,数据已移交给

Notice that in this example data is being 'returned', or more precisely it is being handed off to another unit of work without a thread having to block and wait for a result.

这就是为什么onSuccess返回void的原因,它将在链的末尾使用组成期货。如果要返回一个值,它将类似于map,并且它将返回另一个Future。

This is why onSuccess returns void, it is to be used at the end of a chain of composed futures. If it was to return a value, it would be like map and it would return another Future. Which would leave you with the same requirement of blocking.

因此,回答您的问题,不。不能无止境地从异步的未来中返回价值。相反,您应该查看为什么需要这样返回Response的原因,并查看是否可以将Response的处理转移到onSuccess或map中。一个较小的替代方法是返回Future [Response],并让调用方担心链接期货。您碰到的情况通常发生在混合范例时,最好避免。

Thus to answer your question, no. There is no way to 'return' a value from an asynchronous future without blocking. Instead you should review why you need Response to be returned like that, and see if instead you can move the handling of Response into either onSuccess or map. A minor alternative is to return Future[Response] and let the caller worry about chaining the futures. The case that you have hit usually happens when mixing paradigms, and it is best avoided.

这篇关于如何在Java中异步使用Akka Futures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆