2014-04-21 36 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

相關問題