weixin_33691598 2018-02-20 10:01 采纳率: 0%
浏览 39

Spring Boot异步控制器

I have this post method:

 @PostMapping("/upload")
        public String singleFileUpload(@RequestParam("file") MultipartFile file,RedirectAttributes redirectAttributes)
                throws IOException {
    ExecutorService service= Executors.newSingleThreadExecutor();
            Future<String> future=service.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    //parse file
                    Thread.sleep(5000);
                    return "done";
                }
            });
    String result=future.get();
     service.shutdown();
    return "redirect:uploadState";
    }

I want to redirect to uploadState while executor parse my file and uploadState have long polling ajax to notify if parsing is done or not.Can help me with some hints.

  • 写回答

1条回答 默认 最新

  • weixin_33690367 2018-02-20 11:17
    关注

    Here future.get() is blocker.

    You can use Java 8 CompletableFuture :

    CompletableFuture.supplyAsync(() -> {
        try{
       Thread.sleep(5000);
       return "done";
     }catch(Exception ex){}
    }).thenApply((res->)->{
      return res;
    });
    

    It will not block your control.

    评论

报告相同问题?