我正在使用 spring 进行网络应用程序。一个 API 会执行大量计算,如下所示。
void serviceMethod(){
fetchFromDB();
veryLongComputation1(); //1
veryLongComputation2(); //2
veryLongComputation3(); //3
}
我的 API 需要很长时间才能运行。步骤 1,2 和 3 需要大量时间,因为它们也有大量计算和大量 IO(到数据库)。
我想要的是返回响应并在线程中运行 1,2,3。但这种方法的问题是,如果我的应用程序崩溃,这段代码将永远不会被执行。
有人可以建议一些方法来解决这个问题吗?要记住的一件事是,应用程序会有很多实例。
最佳答案
Java 提供了 async servlet处理需要很长时间才能完成的请求。基本思想是 servlet 容器中的 Http 线程触发计算并立即返回,而只有在计算完成时才发送响应。请参阅下面的示例
@WebServlet(urlPatterns={"/asyncservlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
/* ... Same variables and init method as in SyncServlet ... */
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
final AsyncContext acontext = request.startAsync();
acontext.start(new Runnable() {
public void run() {
String param = acontext.getRequest().getParameter("param");
String result = resource.process(param);
HttpServletResponse response = acontext.getResponse();
/* ... print to the response ... */
acontext.complete();
}
}
spring 中也有同样的事情
@GetMapping(value = "/asyncNonBlockingRequestProcessing")
public CompletableFuture<String> asyncNonBlockingRequestProcessing(){
ListenableFuture<String> listenableFuture = getRequest.execute(new AsyncCompletionHandler<String>() {
@Override
public String onCompleted(Response response) throws Exception {
logger.debug("Async Non Blocking Request processing completed");
return "Async Non blocking...";
}
});
return listenableFuture.toCompletableFuture();
}
关于java - 与反馈异步运行高计算任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908601/