如何在Play Promise中使用Http.Context.current()? [英] How to use Http.Context.current() in a Promise in Play?
问题描述
在Play Framework 2.2.2中,我想返回一个Promise.但是,我正在调用一个函数,该函数需要访问存储在Http.Context.current()
中的变量(当前登录的用户,JPA连接...).
In Play Framework 2.2.2, I'd like to return a Promise. However I'm calling a function which needs access to the variables stored in Http.Context.current()
(the current logged in user, the JPA connection...).
当然,由于Promise是在另一个线程中执行的,因此它无权访问Http.Context.current()
.我可以将其保存在Promise中,还是应该手动还原?我应该使用另一种模式吗?
Of course, since the Promise is executed in another thread, it doesn't have access to Http.Context.current()
. Can I preserve it in the Promise, or should I restore it manually? Is there another pattern I should use?
示例:
public static Promise<Result> getAvailableServices() {
return new Promise.promise(new Function0<Result>(){
@Override
public Result apply() throws Throwable {
// Long operation
List<Services> data = buildResult();
// Render the template
// (The header of the template requires access to
// Http.Context.current().args.get("usermodel"))
return Results.ok(services_template.render(services));
}
});
}
推荐答案
是的,HttpExecutionContext
是您所需要的.
创建HttpExecutionContext
时恢复Http.Context
.
When an HttpExecutionContext
is created it gets the current thread's Http.Context
and stores it. Then, when the HttpExecutionContext
is later used to execute code it restores the Http.Context
.
所有Promise
方法都使用HttpExecutionContext
All Promise
methods use an HttpExecutionContext
wrapped around the default ExecutionContext so they should propagate the Http.Context
correctly across threads.
例如,您的上面的示例代码应该可以正常工作.但是,您确实需要确保当您调用 getAvailableServices
时,Http.Context
在您从其进行调用的线程中可用.如果调用该方法时Http.Context
不可用,则HttpExecutionContext
将无法从该线程中捕获Http.Context
,并且在应用promise的Function0
时将其传播.
Your example code above should work fine, for example. However you do need to make sure that when you call getAvailableServices
, that the Http.Context
is available in the thread you're calling from. If the Http.Context
isn't available when you call the method, then the HttpExecutionContext
will be unable to capture the Http.Context
from that thread and propagate it when the promise's Function0
is applied.
这篇关于如何在Play Promise中使用Http.Context.current()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!