[英]In a verticle, should I use vertx ExecutionContext to execute the completion of a Scala future?
为了摆脱嵌套回调,至少出于可读性考虑,我在vertx应用程序中使用了Scala Futures。
我有一个简单的Verticle处理HTTP请求。 收到请求后,顶点将调用一个方法,该方法执行异步操作并返回Future。 在将来完成时,HTTP响应发送到客户端:
class HttpVerticle extends Verticle with VertxAccess {
val routeMatcher = RouteMatcher()
routeMatcher.get("/test", request => {
println(Thread.currentThread().getName)
// Using scala default ExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global
val future = getTestFilePath()
future.onComplete {
case Success(filename) => {
println(Thread.currentThread().getName)
request.response().sendFile(filename)
}
case Failure(_) => request.response().sendFile("/default.txt")
}
})
def getTestFilePath(): Future[String] = {
// Some async stuff returning a Future
}
}
我注意到,使用通常的(至少对我来说)ExecutionContext,执行将来完成的线程不是顶点池的一部分(这是prinln语句的目的)。 第一个prinln输出vert.x-eventloop-thread-4
而第二个输出ForkJoinPool-1-worker-5
。
然后,我以为我不得不使用vertx执行上下文:
class HttpVerticle extends Verticle with VertxAccess {
val routeMatcher = RouteMatcher()
routeMatcher.get("/test", request => {
println(Thread.currentThread().getName)
// Using vertx execution context
implicit val ec: ExecutionContext = VertxExecutionContext.fromVertxAccess(this)
val future = getTestFilePath()
future.onComplete {
case Success(filename) => {
println(Thread.currentThread().getName)
request.response().sendFile(filename)
}
case Failure(_) => request.response().sendFile("/default.txt")
}
})
def getTestFilePath(): Future[String] = {
// Some async stuff returning a Future
}
}
这样,第一和第二个println将输出vert.x-eventloop-thread-4
。
请注意,这是一个最小的示例。 在我的实际应用程序代码中,我有多个嵌套的回调,因此也链接了期货。
我的问题是:
注意:我正在将vertx 2.1.5与lang-scala 1.0.0一起使用。
我在vert.x Google用户组上从Lars Timm得到了答案 :
是的,您应该使用Vertx特定的执行上下文。 这样可以确保期货在正确的线程/事件循环上运行。 我还没有尝试过使用工人垂直线,但是我不明白为什么它也不能在那里工作。
顺便说一句,您应该考虑使用1.0.1-M1而不是1.0.0。 据我所知,该版本的ExecutionContext中已修复错误。 您也不必导入VertxExecutionContext。 从Verticle / VertxAccess继承时,它会自动完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.