gpt4 book ai didi

Java Spark : Non-blocking routes/callbacks with CompletableFutures

转载 作者:行者123 更新时间:2023-12-02 03:00:31 25 4
gpt4 key购买 nike

我必须在 Spark API 实现中调用长时间运行的方法。这些方法返回 CompletableFutures,因此我想通过触发 Spark 在回调中应答客户端请求来释放当前线程。据我所知,Spark 不可能做到这一点,但我想确保我没有忽略任何事情。为了说明这个问题,请参阅下面的小代码示例。

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";
});
}
}

最佳答案

SparkJava 目前仅处于阻塞状态,因此您所描述的情况是不可能的。有一个开放enhancement request添加对非阻塞 API 的支持。

关于Java Spark : Non-blocking routes/callbacks with CompletableFutures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42434739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com