与反馈异步运行高计算任务

我正在使用spring来开发Web应用程序。一个API进行了大量的计算,如下所示。

void serviceMethod(){
   fetchFromDB();
   veryLongComputation1();  //1
   veryLongComputation2();  //2
   veryLongComputation3();  //3 
}

我的API需要很多时间才能运行。步骤1,2和3需要花费很多时间,因为它们也有很多计算和很多IO(到db)。

我想要的是返回响应并在线程中运行1,2,3。但是这种方法的问题是,如果我的应用程序崩溃了,该代码将永远不会执行。

有人可以提出一些解决此问题的方法吗?要记住的一件事是,会有许多应用程序实例。

wanglaixu0710268 回答:与反馈异步运行高计算任务

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();

    }
本文链接:https://www.f2er.com/3083384.html

大家都在问