博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用spring的异步模式@EnableAsync与@Async配合Future与AsyncResult实现异步调用服务并行,也可以并行sql查询加速系统
阅读量:2059 次
发布时间:2019-04-29

本文共 2252 字,大约阅读时间需要 7 分钟。

spring boot项目

服务类上注解@EnableAsync开启扫描方法上的@Async注解,当其他bean调用这个被@Async注解的方法时,spring会通过代理,在子线程里执行,达到异步调用与并行执行的目的

注意

  1. 不能在类内部 (bean内部,spring无法感知) 调用@Async (就是要),spring无法感知到,所以不会再子线程执行
    @Async生效需要一个bean(controller)调用另一个bean(service)的方法
  2. 如果有返回值,返回值是Future类型的包装
//controller.java    @Autowired    private FakeService fakeService;    @GetMapping("/slow")    public String slow() {        StopWatch watch = new StopWatch("my watch");        //通常模式service调用        watch.start("slowServiceNormal");        fakeService.slowService();        fakeService.slowService();        watch.stop();        //异步模式,在子线程各自独立调用service,有返回值        watch.start("slowService async with return");        Future
res1 = fakeService.slowServiceAsync(); Future
res2 = fakeService.slowServiceAsync(); try { res1.get(); res2.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } watch.stop(); //无返回值调用,直接返回,子线程继续工作 watch.start("slowServiceNoReturn"); fakeService.slowServiceNoReturn(); fakeService.slowServiceNoReturn(); watch.stop(); System.out.println(watch.prettyPrint()); return "done"; }
package boottest;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.AsyncResult;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.stereotype.Service;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.LockSupport;/** * @author zhanghui * @date 2019/5/9 */@Service@EnableAsyncpublic class FakeService {    public long slowService(){        System.out.println("slowServiceNormal");        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));        System.out.println("slowServiceNormal done");        return 5;    }    //异步调用,有返回值,必须是Future类型,不然报错    @Async    public Future
slowServiceAsync(){ System.out.println("slowServiceAsync"); return new AsyncResult(slowService()); } @Async public void slowServiceNoReturn(){ System.out.println("slowServiceNoReturn"); slowService(); }}

转载地址:http://xyalf.baihongyu.com/

你可能感兴趣的文章
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>
阿里云《云原生》公开课笔记 第七章 应用编排与管理:Job和DaemonSet
查看>>
阿里云《云原生》公开课笔记 第八章 应用配置管理
查看>>
阿里云《云原生》公开课笔记 第九章 应用存储和持久化数据卷:核心知识
查看>>
linux系统 阿里云源
查看>>
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>
Leetcode C++《每日一题》20200622 面试题 16.18. 模式匹配
查看>>
Leetcode C++《每日一题》20200625 139. 单词拆分
查看>>
Leetcode C++《每日一题》20200626 338. 比特位计数
查看>>
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>