How to use Http.Context.current() in a Promise in Play?

梦想的初衷 提交于 2019-11-28 04:44:49

问题


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...).

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?

Example:

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

回答1:


Yes, HttpExecutionContext is what you need.

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.

All Promise methods use an HttpExecutionContext wrapped around the default ExecutionContext so they should propagate the Http.Context correctly across threads.

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.



来源:https://stackoverflow.com/questions/23198375/how-to-use-http-context-current-in-a-promise-in-play

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!