zoukankan      html  css  js  c++  java
  • springboot异步处理请求 带返回值的情况

    package yinhu.yinhu.controller;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import yinhu.yinhu.yh.vo.AsyncTest;
    
    @Controller
    @EnableAsync
    public class AsyncController {
        @Autowired
        private AsyncTest asyncTest;
        @ResponseBody
        @GetMapping
        @RequestMapping(value="/async")
        public String test() {
            Future<String> future=asyncTest.mywait();
            String s = null;
            try {
                 s=future.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("wait");
            return s;
        }
    
    }
    package yinhu.yinhu.yh.vo;
    
    import java.util.concurrent.Future;
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.AsyncResult;
    import org.springframework.stereotype.Component;
    
    @Component
    public class AsyncTest {
        @Async
        public Future<String> mywait() {
            System.out.println("------------------oh no");
            Future<String> returnmsg;
            try {
                Thread.sleep(1000*10);
                
                System.out.println("线程名字"+Thread.currentThread().getName());
                returnmsg=new AsyncResult<String>("sucess");//没异常就返回这个
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                returnmsg=new AsyncResult<String>("异常为"+e.getMessage());
            }
            System.out.println("------------------oh yes");
            return returnmsg;
        }
    }
  • 相关阅读:
    JS开发技巧
    Git push 常见用法
    关闭浏览器标签
    vue 样式穿透 watch深度监听
    Git Commit Template 提交模板
    常用git stash命令:
    Windows下安装及使用NVM
    JS正则表达式
    js转码
    多行文本溢出显示省略号(…)全攻略
  • 原文地址:https://www.cnblogs.com/qinyios/p/12551652.html
Copyright © 2011-2022 走看看