[英]How do I start a background thread with a request in the Play! framework?
[英]how do I suspend a request in Play Framework?
我在玩 Play 框架 (v2.2.2),我正在尝试弄清楚如何挂起 HTTP 请求。 我正在尝试在用户之间创建握手,这意味着我希望用户 A 能够发出请求并等待用户 B“连接”。 一旦用户 B 连接,用户 A 的请求应该返回一些信息(信息无关紧要;现在我们只说一些 JSON)。
在我开发的另一个应用程序中,我使用延续来暂停和重放 HTTP 请求,所以我有这样的事情......
@Override
public JsonResponse doGet(HttpServletRequest request, HttpServletResponse response) {
Continuation reqContinuation = ContinuationSupport.getContinuation(request);
if (reqContinuation.isInitial()) {
...
reqContinuation.addContinuationListener(new ContinuationListener() {
public void onTimeout(Continuation c) {...}
public void onComplete(Continuation c) {...}
});
...
reqContinuation.suspend();
return null;
}
else {
// check results and return JsonResponse with data
}
}
...并且在某些时候,用户 B 将连接并且延续将在不同的 servlet 中恢复/完成。 现在,我想弄清楚如何在 Play 中做到这一点。 我已经设置了我的路线...
GET /test controllers.TestApp.test()
......我有我的行动......
public static Promise<Result> test() {
Promise<JsonResponse> promise = Promise.promise(new Function0<JsonResponse>() {
public JsonResponse apply() {
// what do I do now...?
// I need to wait for user B to connect
}
});
return promise.map(new Function<JsonResponse, Result>() {
public Result apply(JsonResponse json) {
return ok(json);
}
});
}
我很难理解如何构建我的 Promise。 本质上,我需要告诉用户 A“嘿,您正在等待用户 B,所以这里承诺用户 B 最终会连接到您,否则我会在您不必再等待时通知您” .
如何暂停请求,以便我可以返回用户 B 连接的承诺? 如何等待用户 B 连接?
您需要创建一个可以在以后赎回的Promise
。 奇怪的是,Play/Java 库 ( F.java ) 似乎没有公开这个 API,所以你必须进入Scala Promise 类。
为自己创建一个小的 Scala 辅助类PromiseUtility.scala
:
import scala.concurrent.Promise
object PromiseUtility {
def newPromise[T]() = Promise[T]()
}
然后你可以在控制器中做这样的事情(注意,我不完全理解你的用例,所以这只是如何使用这些Promises
的粗略概述):
if (needToWaitForUserB()) {
// Create an unredeemed Scala Promise
scala.concurrent.Promise<Json> unredeemed = PromiseUtility.newPromise();
// Store it somewhere so you can access it later, e.g. a ConcurrentMap keyed by userId
storeUnredeemed(userId, unredeemed);
// Wrap as an F.Promise and, when redeemed later on, convert to a Result
return F.Promise.wrap(unredeemed.future()).map(new Function<Json, Result>() {
@Override
public Result apply(Json json) {
return ok(json);
}
});
}
// [..]
// In some other part of the code where user B connects
scala.concurrent.Promise<Json> unredeemed = getUnredeemed(userId);
unredeemed.success(jsonDataForUserB);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.