cats-effect
在我的 Play 应用程序中,我使用's服务我的请求IO
,而不是Future
在控制器中,像这样(超级简化):
def handleServiceResult(serviceResult: ServiceResult): Result = ...
def serviceMyRequest(request: Request): IO[ServiceResult] = ...
def myAction = Action { request =>
handleServiceResult(
serviceMyRequest(request).unsafeRunSync()
)
}
然后在 Play 的默认线程池上(异步)处理请求。现在,我想实现多个线程池来处理不同类型的请求。如果我使用Future
s,我可以这样做:
val myCustomExecutionContext: ExecutionContext = ...
def serviceMyRequest(request: Request): Future[ServiceResult] = ...
def myAction = Action.async { request =>
Future(serviceMyRequest(request))(myCustomExecutionContext)
.map(handleServiceResult)(defaultExecutionContext)
}
但我没有使用Future
s,我正在使用IO
,而且我不确定实现它的正确方法。这看起来很有希望,但似乎有点笨拙:
def serviceMyRequest(request: Request): IO[ServiceResult] = ...
def myAction = Action { request =>
val ioServiceResult = for {
_ <- IO.shift(myCustomExecutionContext)
serviceResult <- serviceMyRequest(request)
_ <- IO.shift(defaultExecutionContext)
} yield {
serviceResult
}
handleServiceResult(ioServiceResult.unsafeRunSync())
}
这是实施它的正确方法吗?这里有最佳实践吗?我搞砸了吗?谢谢。