2014-04-21 33 views
2

在Play Framework 2.2.2中,我想返回一个Promise。不过,我正在调用一个需要访问存储在Http.Context.current()(当前登录用户,JPA连接...)中的变量的函数。如何在播放Promise中使用Http.Context.current()?

当然,由于Promise在另一个线程中执行,因此它无权访问Http.Context.current()。我可以保留它在承诺,还是我应该手动恢复它?我应该使用另一种模式吗?

例子:

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)); 
     } 
    }); 
} 
+0

此问题可能被认为是http://stackoverflow.com/questions/17886630/play-2-1-1-java-can-i-access-http-context-current-from-an-任意异步 – Adrien

+0

我们可以将另一个参数传递给Promise.promise(),ExecutionContext。 [HttpExecutionContext](http://www.playframework.com/documentation/2.2.1/api/scala/index.html#play.core.j.HttpExecutionContext)是答案的一部分吗? – Adrien

回答

5

是,HttpExecutionContext是你所需要的。

当创建一个HttpExecutionContext时,它。然后,当HttpExecutionContext后来用于执行代码it restores the Http.Context

All Promise methods use an HttpExecutionContextwrapped around the default ExecutionContext因此他们应该跨线程正确传播Http.Context。例如,上面的示例代码应该可以正常工作。但是,您确实需要确保当您拨打致电getAvailableServices时,Http.Context在您打来的线索中可用。如果调用该方法时Http.Context不可用,则HttpExecutionContext将无法​​从该线程捕获Http.Context,并在应用承诺的Function0时传播它。

+1

它的工作原理!我使用'''Promise.promise(...,HttpExecution.defaultContext())'''。非常感谢你! – Adrien

相关问题