我正在尝试转换阻塞的Play框架控制器操作,如下所示:
public Result testSync(String param1, String param2) {
String result1 = <LONG-DB-QUERY>;
if (result1 == null) {
return internalServerError();
}
if (result1.equals("<SOME VALUE>")) {
return ok(param1);
}
String result2 = <LONG-DB-QUERY>;
return ok(result1 + result2);
}
使用Future
接口进入非阻止代码,即返回CompletionStage<Result>
如您所见,我需要result1
和result2
。我假设我无法使用supplyAsync
和thenCombine
,因为只有在某些情况下才需要计算result2
。
答案 0 :(得分:1)
好的,基于similar answer这就是我设法做到的方式:
public CompletionStage<Result> testAsync(String param1, String param2) {
CompletableFuture<Result> shortCut = new CompletableFuture<>();
CompletableFuture<String> withChain = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
String result1 = <LONG-DB-QUERY>;
if (result1 == null) {
shortCut.complete(internalServerError());
return;
}
if (result1.equals("<SOME VALUE>")) {
shortCut.complete(ok(param1));
return;
}
withChain.complete(result1);
});
return withChain
.thenCombine(CompletableFuture.supplyAsync(() -> <LONG-DB-QUERY>), (newParam1, newParam2) -> ok(result1+result2))
.applyToEither(shortCut, Function.identity());
}