0
我必须在Spark API实现中调用长时间运行的方法。这些方法返回CompletableFutures,所以我想通过触发Spark在回调中回答客户端请求来释放当前的线程。 据我可以告诉这是不可能与Spark,但我想确保我不俯瞰任何东西。 为了说明这个问题,请参阅下面的小代码示例。Java Spark:CompletableFutures的非阻塞路由/回调
import spark.Spark;
import java.util.concurrent.CompletableFuture;
public class HelloSpark {
public static void main(String[] args) {
Spark.get("/what_i_have_to_do", (req, res) -> {
CompletableFuture<String> f = callToSlowWorker();
return f.get();
});
Spark.get("/what_i_would_like_to_do", (req, res) -> {
CompletableFuture<String> f = callToSlowWorker();
f.whenComplete((answer, throwable) -> {
if(throwable != null){
// send error to requesting client
res.status(500);
res.body(throwable.getMessage());
} else {
// send answer to requesting client
res.body(answer);
}
// trigger spark to return the response to the client
// ...?!?
});
return null; // obviously not what I want, just to make this sample code compile
});
}
static CompletableFuture<String> callToSlowWorker(){
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
return "Hello World";
});
}
}