天天看点

springboot 的异步任务 :无返回值 和有返回值

在想要异步执行的方法上加上@Async注解,在controller上加上@EnableAsync,即可。

注:这里的异步方法,只能在本类之外调用,在本类调用是无效的。

无返回值的异步任务

service实现部分:

@Service
public class AsyncService {
 
    @Async //想要异步执行的方法上加@Async 注解
    public void doNoReturn(){
        try {
            // 这个方法执行需要三秒
            Thread.sleep(3000);
            System.out.println("方法执行结束" + new Date());
        } catch (InterruptedException e) {
            e.printStackTrace();
    }
}
           

controller调用部分:

@RestController
@EnableAsync//调用异步任务的controller上加@EnableAsync注解
public class AsyncController {
    @Autowired
    private AsyncService asyncService;
 
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String testAsyncNoRetrun(){
        long start = System.currentTimeMillis();
         asyncService.doNoReturn();
         return String.format("任务执行成功,耗时{%s}", System.currentTimeMillis() - start);
    }
           

输出:

任务执行成功,耗时{4}
           

可见testAsyncNoRetrun()方法中 调用doNoReturn(),没等doNoReturn()执行完即返回。

有返回值的异步任务

有返回值的异步任务方法需要用Futrue变量把返回值封装起来。

service实现部分:

@Async
 public Future<String> doReturn(int i){
        try {
            // 这个方法需要调用500毫秒
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 消息汇总
        return new AsyncResult<>(String.format("这个是第{%s}个异步调用的证书", i));
}
           

读取的时候要批量读取不能单独读取。

controller调用部分:

@GetMapping("/hi")
    public Map<String, Object> testAsyncReturn() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
 
        Map<String, Object> map = new HashMap<>();
        List<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<String> future = asyncService.doReturn(i);
            futures.add(future);
        }
        List<String> response = new ArrayList<>();
        for (Future future : futures) {
            String string = (String) future.get();
            response.add(string);
        }
        map.put("data", response);
        map.put("消耗时间", String.format("任务执行成功,耗时{%s}毫秒", System.currentTimeMillis() - start));
        return map;
}
           

在浏览器输入地址:http://localhost:8080/hi

结果如下: 耗时500多毫秒的意思代表,springboot自带异步任务线程池是小于10的大小的

{"data":["这个是第{0}个异步调用的证书","这个是第{1}个异步调用的证书","这个是第{2}个异步调用的证书","这个是第{3}个异步调用的证书","这个是第{4}个异步调用的证书","这个是第{5}个异步调用的证书","这个是第{6}个异步调用的证书","这个是第{7}个异步调用的证书","这个是第{8}个异步调用的证书","这个是第{9}个异步调用的证书"],"消耗时间":"任务执行成功,耗时{508}毫秒"}
           

继续阅读