spring boot 使用@Async实现异步调用方法
使用@Async实现异步调用 什么是”异步调用”与”同步调用” “同步调用”就是程序按照一定的顺序依次执行,,每一行程序代码必须等上一行代码执行完毕才能执行;”异步调用”则是只要上一行代码执行,无需等待结果的返回就开始执行本身任务。 “异步调用” 在 spring boot 框架中,只要提过@Async注解就能奖普通的同步任务改为异步调用任务。 1. 开启@Async注解 在Spring Boot主类添加@EnableAsync注解 2. 定义异步任务 定义Task类,创建三个处理函数分别模拟三个执行任务的操作,操作消耗时间随机取(10秒内)。 @Component public class Task { //定义一个随机对象. public static Random random =new Random(); @Async //加入"异步调用"注解 public void doTaskOne() throws InterruptedException { System.out.println("开始执行任务一"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); } @Async public void doTaskTwo() throws InterruptedException { System.out.println("开始执行任务二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); } @Async public void doTaaskThree() throws InterruptedException { System.out.println("开始执行任务三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); } } 3. 创建Controller进行测试 注意@Autowired注入类,因为这个类已经被 Spring 管理了。如果使用 new 来获得线程类将不会执行异步效果,这里涉及到在 Spring 中使用多线程。 @Controller public class TaskController { @Autowired private Task TASK; @ResponseBody @RequestMapping("/task") public String task() throws Exception { System.out.println("开始执行Controller任务"); long start = System.currentTimeMillis(); TASK.doTaskOne(); TASK.doTaskTwo(); TASK.doTaaskThree(); long end = System.currentTimeMillis(); System.out.println("完成Controller任务,耗时:" + (end - start) + "毫秒"); return "success"; } } 4. 多次调用 访问 http://localhost:8080/task 截图: 项目参考地址: https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B7 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |