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.

    评论

报告相同问题?

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表