簡體   English   中英

如何在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM