Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

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

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));
        }
    });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...