• SpringBoot+@Async=王炸


    异步调用几乎是处理高并发Web应用性能问题的万金油,那么什么是“异步调用”?异步调用对应的是同步调用

    • 异步调用:指程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序
    • 同步调用:指程序按照定义顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行;

    同步调用

    定义一个同步任务

    @Component
    public class AsyncTask {
        public static Random random = new Random();
    
        @Async
        public void doTaskOne() throws InterruptedException {
            System.out.println("开始做任务一");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务一,耗时: " + (end - start) + "毫秒");
        }
    
        @Async
        public void doTaskTwo() throws InterruptedException {
            System.out.println("开始做认为二");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        }
    
        @Async
        public void doTaskThree() throws InterruptedException {
            System.out.println("开始做任务三");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    然后编写单元测试

    @Test
    public void testSync() throws Exception {
        syncTask.doTaskOne();
        syncTask.doTaskTwo();
        syncTask.doTaskThree();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    执行单元测试,结果如下:

    开始做任务一
    完成任务一,耗时: 6003毫秒
    开始做认为二
    完成任务二,耗时:1003毫秒
    开始做任务三
    完成任务三,耗时:4009毫秒
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    异步调用

    上述的同步调用虽然顺利的执行完成了三个任务,但是可以看到执行时间比较长,若这三个任务本身之间不存在依赖关系,可以并发执行的话,同步调用在执行效率方面就比较差,可以考虑通过异步调用的方式来并发执行。
    在SpringBoot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数。此外,还需要在SpringBoot的主程序中配置@EnableAsync注解

    @SpringBootApplication
    @EnableAsync
    public class AsyncApplication {
        public static void main(String[] args) {
            SpringApplication.run(AsyncApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    @Component
    public class AsyncTask {
        public static Random random = new Random();
    
        @Async
        public void doTaskOne() throws InterruptedException {
            System.out.println("开始做任务一");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务一,耗时: " + (end - start) + "毫秒");
        }
    
        @Async
        public void doTaskTwo() throws InterruptedException {
            System.out.println("开始做认为二");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
        }
    
        @Async
        public void doTaskThree() throws InterruptedException {
            System.out.println("开始做任务三");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    此时,你可以反复执行单元测试,你可能会遇到各种不同的结果,比如

    • 没有任何任务相关的输出
    • 有部分任务相关的输出
    • 乱序的任务相关的输出
      原因是,目前doTaskOne、doTaskTwo、doTaskThree三个函数的时候已经是异步执行了。
      主程序在异步调用之后,主程序并不会理会这三个函数是否执行完成了,由于没有其他需要执行的内容,所以程序就自动结束了,导致了不完整或是没有输出任务相关内容的情况

    注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

    异步回调

    为了让doTaskOne、doTaskTwo、doTaskThree能正常结束,假设我们需要统计一下三个任务并发执行共耗时多少,这就需要等到上述三个函数都完成调用之后记录时间,并计算结果。
    异步任务函数改造

    @Component
    public class FutureAsyncTask {
        public static Random random = new Random();
    
        @Async
        public Future<String> doTaskOne() throws InterruptedException {
            System.out.println("开始做任务一");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务一,耗时: " + (end - start) + "毫秒");
            return new AsyncResult<>("任务一完成");
        }
    
        @Async
        public Future<String> doTaskTwo() throws InterruptedException {
            System.out.println("开始做认为二");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
            return new AsyncResult<>("任务二完成");
        }
    
        @Async
        public Future<String> doTaskThree() throws InterruptedException {
            System.out.println("开始做任务三");
            long start = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(random.nextInt(10));
            long end = System.currentTimeMillis();
            System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
            return new AsyncResult<>("任务三完成");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    编写测试用例

    @Test
    public void testFutureAsync() throws InterruptedException {
         long start = System.currentTimeMillis();
         Future<String> task1 = futureAsyncTask.doTaskOne();
         Future<String> task2 = futureAsyncTask.doTaskTwo();
         Future<String> task3 = futureAsyncTask.doTaskThree();
         while (Boolean.TRUE) {
             if (task1.isDone() && task2.isDone() && task3.isDone()) {
                 // 三个任务都调用完成,退出循环等待
                 break;
             }
             TimeUnit.SECONDS.sleep(1);
         }
         long end = System.currentTimeMillis();
    
         System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    看看我们做了哪些改变

    • 在测试用例一开始记录开始时间
    • 在调用三个异步函数的时候,返回Future类型的结果对象
    • 在调用完三个异步函数之后,开启一个循环,根据返回的Future对象来判断三个异步函数是否都结束了。若都结束,就结束循环;若没有都结束,就等1秒后再判断
    • 跳出循环之后,根据开始时间和结束使劲按计算出三个任务并发执行的总耗时
    开始做认为二
    开始做任务三
    开始做任务一
    完成任务一,耗时: 3013毫秒
    完成任务三,耗时:5002毫秒
    完成任务二,耗时:9013毫秒
    任务全部完成,总耗时:9075毫秒
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    现在我们在异步函数上添加static,使其成为静态函数,IDEA会警告
    在这里插入图片描述
    用“@Async”注释的方法必须是可重写的

  • 相关阅读:
    【C++】搜索二叉树/KVL树
    中文drupal教程1. 自动加载器与Composer
    上市公司排污费2010-2020&重污染行业环境披露水平-原始数据及计算结果
    HTTP、TCP、SOCKET三者之间区别和原理
    SwiftUI 高级教程之可组合的通用 SwiftUI 视图
    git基本使用
    《大数据项目实战之搜索引擎用户行为分析》
    Mysql查询(SELECT)
    【从零开始学习 UVM】1.3、UVM 概述 —— UVM Introduction
    使用kubeadm快速部署一个K8s集群
  • 原文地址:https://blog.csdn.net/qq_42582773/article/details/126744391