如何在 Play 中的 Promise 中使用 Http.Context.current()? [英] How to use Http.Context.current() in a Promise in Play?

查看:17
本文介绍了如何在 Play 中的 Promise 中使用 Http.Context.current()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 正是您所需要的.

Yes, HttpExecutionContext is what you need.

HttpExecutionContext 被创建时,它 获取当前线程的Http.Context并保存.然后,当 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 环绕默认的ExecutionContext所以他们应该传播Http.Context 正确跨线程.

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线程并在应用承诺的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆