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;
    }
}

 

posted @ 2020-03-23 13:22  黑魔法os  阅读(5325)  评论(0编辑  收藏  举报