在Akka中直接使用期货 [英] direct use of Futures in Akka

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

问题描述

我无法按照此处。它说您可以使用以下代码直接创建 Future

I am not able to create a Future as explained here. It says you can create a Future directly using the following code:

import akka.dispatch.Await
import akka.dispatch.Future
import akka.util.duration._

val future  = Future {
  "Hello" + "World"
}
val result = Await.result(future, 1 second)

使用完全相同的代码,我收到一条错误消息,说:错误:找不到参数执行程序akka.dispatch.ExecutionContext 的隐式值。关于 ExecutionContext 我所能找到的就是,您可以用它做事。在文档中,我发现的唯一行是:

Using the exact same code, I get an errormessage, saying: error: could not find implicit value for parameter executor: akka.dispatch.ExecutionContext. All I can find about the ExecutionContext is, that you can "do stuff" with it. In the documentation, the only line I found was:

implicit val ec = ExecutionContect.fromExecutionService(yourExecutionServiceGoesHere)

但这对我没有用。有人对我有任何建议吗?如何在不要求 Actor 的情况下创建新的 Future

But this was not usefull to me. Has anyone any suggestion on that topic for me? How can I create a new Future without asking an Actor?

推荐答案

如果您有 ActorSystem ,那么它将具有 ExecutionContext 可以在这里使用。它必须是隐式,除非您将其显式传递给 Future.apply 方法。

If you have an ActorSystem then it will have an ExecutionContext which can be used here. It must be implicit, unless you pass it explicitly to the Future.apply method.

出于演示目的,如果您仅想查看它在REPL中的工作方式,

For the purposes of demonstration, if you just want to see how this works in the REPL:

implicit val system = ActorSystem("MySystem").dispatcher

(还有一个隐式转换 ActorSystem =>在 ExecutionContext 对象上的ExecutionContext 。)

(There is also an implicit conversion ActorSystem => ExecutionContext on the ExecutionContext object.)

要创建模块化代码而不在使用之前创建上下文,请考虑使上下文成为特征的抽象成员:

To create modular code, without creating a context just before the point of use, consider making the context an abstract member of a trait:

trait MyFutures {
  implicit val context: ExecutionContext

  def helloFuture: Future[String] = Future { "hello" + "world" }
}

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

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