SpringBoot实现异步调用的几种方式_springboot 异步方法-程序员宅基地

技术标签: java  开发语言  

一、使用 CompletableFuture 实现异步任务

CompletableFuture 是 Java 8 新增的一个异步编程工具,它可以方便地实现异步任务。使用 CompletableFuture 需要满足以下条件:

  1. 异步任务的返回值类型必须是 CompletableFuture 类型;

  2. 在异步任务中使用 CompletableFuture.supplyAsync() 或 CompletableFuture.runAsync() 方法来创建异步任务;

  3. 在主线程中使用 CompletableFuture.get() 方法获取异步任务的返回结果。

我们创建一个服务类,里面包含了异步方法和普通方法。

import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步服务类
 */
@Service
public class AsyncService {


    /**
     * 普通任务操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成1";
    }

    /**
     * 普通任务操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任务执行完成2";
    }

    /**
     * 普通任务操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成3";
    }

    /**
     * 异步操作1
     */
    public CompletableFuture<String> asyncTask1() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "异步任务执行完成1";
        });
    }

    /**
     * 异步操作2
     */
    public CompletableFuture<String> asyncTask2() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "异步任务执行完成2";
        });
    }

    /**
     * 异步操作3
     */
    public CompletableFuture<String> asyncTask3() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "异步任务执行完成3";
        });
    }
}

我们先测试普通方法的情况,看看最后耗时

import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步处理测试
 */
@SpringBootTest
public class AsyncTest {

    @Autowired
    private AsyncService asyncService;

    @Test
    void test1() throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 异步操作
       /* CompletableFuture<String> completableFuture1 = asyncService.asyncTask1();
        CompletableFuture<String> completableFuture2 = asyncService.asyncTask2();
        CompletableFuture<String> completableFuture3 = asyncService.asyncTask3();

        System.out.println(completableFuture1.get());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture3.get());*/

        // 同步操作
        System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());

        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
    }
}

程序执行的结果:

任务执行完成1
任务执行完成2
任务执行完成3
耗时:8008

我们可以发现,普通同步方法是按顺序一个个操作的,各个方法不会同时处理。下面我们把这些操作换成异步的方法测试。

import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步处理测试
 */
@SpringBootTest
public class AsyncTest {

    @Autowired
    private AsyncService asyncService;

    @Test
    void test1() throws InterruptedException, ExecutionException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 异步操作
        CompletableFuture<String> completableFuture1 = asyncService.asyncTask1();
        CompletableFuture<String> completableFuture2 = asyncService.asyncTask2();
        CompletableFuture<String> completableFuture3 = asyncService.asyncTask3();

        System.out.println(completableFuture1.get());
        System.out.println(completableFuture2.get());
        System.out.println(completableFuture3.get());

        // 同步操作
        /*System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());*/

        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
    }
}

程序执行结果:

异步任务执行完成1
异步任务执行完成2
异步任务执行完成3
耗时:3008

发现几个方法是异步同时进行的,没有先后的顺序,大大提高了程序执行效率。

二、基于注解 @Async实现异步任务

@Async 注解是 Spring 提供的一种轻量级异步方法实现方式,它可以标记在方法上,用来告诉 Spring 这个方法是一个异步方法,Spring 会将这个方法的执行放在异步线程中进行。使用 @Async 注解需要满足以下条件:

  1. 需要在 Spring Boot 主类上添加 @EnableAsync 注解启用异步功能;

  2. 需要在异步方法上添加 @Async 注解。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
// 主类上加上这个注解,开启异步功能
@EnableAsync
public class QuartzDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(QuartzDemoApplication.class, args);
    }

}

修改测试的服务层

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步服务类
 */
@Service
public class AsyncService {


    /**
     * 同步任务操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成1";
    }

    /**
     * 同步任务操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任务执行完成2";
    }

    /**
     * 同步任务操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成3";
    }


    /**
     * 异步操作1
     */
    @Async
    public Future<String> asyncTask1() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(3);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任务耗时:" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task1完成");
    }

    /**
     * 异步操作2
     */
    @Async
    public Future<String> asyncTask2() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任务耗时:" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task2完成");
    }

    /**
     * 异步操作3
     */
    @Async
    public Future<String> asyncTask3() throws InterruptedException {
        long currentTimeMillis = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(3);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任务耗时:" + (currentTimeMillis1 - currentTimeMillis) + "ms");
        return new AsyncResult<>("task3完成");
    }

}

创建一个测试类

import com.example.quartzdemo.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion:
 */
@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    /**
     * 测试异步
     */
    @RequestMapping("/async")
    public String testAsync() throws InterruptedException, ExecutionException {
        long currentTimeMillis = System.currentTimeMillis();

        Future<String> task1 = asyncService.asyncTask1();
        Future<String> task2 = asyncService.asyncTask2();
        Future<String> task3 = asyncService.asyncTask3();
        while (true) {
            if (task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
        }
        System.out.println(task1.get());
        System.out.println(task2.get());
        System.out.println(task3.get());
        long currentTimeMillis1 = System.currentTimeMillis();
        return "task任务总耗时:" + (currentTimeMillis1 - currentTimeMillis) + "ms";
    }
}

执行测试方法

task1任务耗时:2006ms
task1任务耗时:3011ms
task1任务耗时:3011ms
task1完成
task2完成
task3完成

三、使用 TaskExecutor 实现异步任务

TaskExecutor 是 Spring 提供的一个接口,它定义了一个方法 execute(),用来执行异步任务。使用 TaskExecutor 需要满足以下条件:

  1. 需要在 Spring 配置文件中配置一个 TaskExecutor 实例;

  2. 在异步方法中调用 TaskExecutor 实例的 execute() 方法来执行异步任务。

创建一个异步配置类

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步处理配置类
 */
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Bean(name = "asyncExecutor")
    public TaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("async-");
        executor.initialize();
        return executor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

修改下服务类,我们使用自定义的异步配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步服务类
 */
@Service
public class AsyncService {

    @Autowired
    @Qualifier("asyncExecutor")
    private TaskExecutor taskExecutor;


    /**
     * 同步任务操作1
     */
    public String task1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成1";
    }

    /**
     * 同步任务操作2
     */
    public String task2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        return "任务执行完成2";
    }

    /**
     * 同步任务操作3
     */
    public String task3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
        return "任务执行完成3";
    }


    /**
     * 异步操作1
     */
    @Async
    public void asyncTask1() {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("异步任务执行完成1");
    }

    /**
     * 异步操作2
     */
    @Async
    public void asyncTask2() throws InterruptedException {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("异步任务执行完成2");
    }

    /**
     * 异步操作3
     */
    @Async
    public void asyncTask3() throws InterruptedException {
        taskExecutor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println("异步任务执行完成3");
    }
    
}

测试类进行测试

/**
 * @author qinxun
 * @date 2023-06-07
 * @Descripion: 异步处理测试
 */
@SpringBootTest
public class AsyncTest {
    
    @Autowired
    @Qualifier("asyncExecutor")
    private TaskExecutor taskExecutor;


    @Test
    void test1() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 异步操作
       /* asyncService.asyncTask1();
        asyncService.asyncTask2();
        asyncService.asyncTask3();*/
        taskExecutor.execute(() -> System.out.println("异步任务"));

        // 同步操作
        /*System.out.println(asyncService.task1());
        System.out.println(asyncService.task2());
        System.out.println(asyncService.task3());*/

        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
    }
}
耗时:6
异步任务执行完成3
异步任务执行完成1
异步任务执行完成2

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qinxun2008081/article/details/131093083

智能推荐

【新手科研指南5】深度学习代码怎么读-小白阶段性思路(以手写数字识别应用为例)_深度学习程序怎么读-程序员宅基地

文章浏览阅读6.2k次,点赞6次,收藏26次。我是一个深度学习代码小白,请你用中文写上注释,能让我能轻松理解下面这段代码。注意包含所有函数、调用和参数的注释。以同样的python代码块样式返回你写的代码给我。代码看累了,就看《动手学深度学习》文档:基于PyTorch框架,从底层函数实现基础功能,再到框架的高级功能。努力上路的小白一枚,麻烦路过的大佬指导一二,同时希望能和大家交流学习~争取更新学习这个文档的专栏,记录学习过程。量身定做了一套话术hhh,亲身测试还不错。这个感觉更浅一点儿,之后复习看吧。20天吃掉那只Pytorch。_深度学习程序怎么读

Java学习路线图,看这一篇就够了!-程序员宅基地

文章浏览阅读2.7w次,点赞126次,收藏1.2k次。耗废1024根秀发,Java学习路线图来了,整合了自己所学的所有技术整理出来的2022最新版Java学习路线图,适合于初、中级别的Java程序员。_java学习路线

PCL_Tutorial2-1.7-点云保存PNG_pcl::io:savepng-程序员宅基地

文章浏览阅读4.4k次。1.7-savingPNG介绍代码详情函数详解savePNGFile()源码savePNGFile()源码提示savePNGFile()推荐用法处理结果代码链接介绍PCL提供了将点云的值保存到PNG图像文件的可能性。这只能用有有序的云来完成,因为结果图像的行和列将与云中的行和列完全对应。例如,如果您从类似Kinect或Xtion的传感器中获取了点云,则可以使用它来检索与该云匹配的640x480 RGB图像。代码详情#include <pcl / io / pcd_io.h>#incl_pcl::io:savepng

知乎问答:程序员在咖啡店编程,喝什么咖啡容易吸引妹纸?-程序员宅基地

文章浏览阅读936次。吸引妹子的关键点不在于喝什么咖啡,主要在于竖立哪种男性人设。能把人设在几分钟内快速固定下来,也就不愁吸引对口的妹子了。我有几个备选方案,仅供参考。1. 运动型男生左手单手俯卧撑,右手在键盘上敲代码。你雄壮的腰腹肌肉群活灵活现,简直就是移动的春药。2.幽默男生花 20 块找一个托(最好是老同学 or 同事)坐你对面。每当你侃侃而谈,他便满面涨红、放声大笑、不能自已。他笑的越弱_咖啡厅写代码

【笔试面试】腾讯WXG 面委会面复盘总结 --一次深刻的教训_腾讯面委会面试是什么-程序员宅基地

文章浏览阅读1.2w次,点赞5次,收藏5次。今天 (应该是昨天了,昨晚太晚了没发出去)下午参加了腾讯WXG的面委会面试。前面在牛客上搜索了面委会相关的面经普遍反映面委会较难,因为都是微信的核心大佬,问的问题也会比较深。昨晚还蛮紧张的,晚上都没睡好。面试使用的是腾讯会议,时间到了面试官准时进入会议。照例是简单的自我介绍,然后是几个常见的基础问题:例如数据库索引,什么时候索引会失效、设计模式等。这部分比较普通,问的也不是很多,不再赘述。现在回想下,大部分还是简历上写的技能点。接下来面试官让打开项目的代码,对着代码讲解思路。我笔记本上没有这部分代码,所_腾讯面委会面试是什么

AI绘画自动生成器:艺术创作的新浪潮-程序员宅基地

文章浏览阅读382次,点赞3次,收藏4次。AI绘画自动生成器是一种利用人工智能技术,特别是深度学习算法,来自动创建视觉艺术作品的软件工具。这些工具通常基于神经网络模型,如生成对抗网络(GANs),通过学习大量的图像数据来生成新的图像。AI绘画自动生成器作为艺术与科技结合的产物,正在开启艺术创作的新篇章。它们不仅为艺术家和设计师提供了新的工具,也为普通用户提供了探索艺术的机会。随着技术的不断进步,我们可以预见,AI绘画自动生成器将在未来的创意产业中发挥越来越重要的作用。

随便推点

Flutter ListView ListView.build ListView.separated_flutter listview.separated和listview.builder-程序员宅基地

文章浏览阅读1.7k次。理解为ListView 的三种形式吧ListView 默认构造但是这种方式创建的列表存在一个问题:对于那些长列表或者需要较昂贵渲染开销的子组件,即使还没有出现在屏幕中但仍然会被ListView所创建,这将是一项较大的开销,使用不当可能引起性能问题甚至卡顿直接返回的是每一行的Widget,相当于ios的row。行高按Widget(cell)高设置ListView.build 就和io..._flutter listview.separated和listview.builder

2021 最新前端面试题及答案-程序员宅基地

文章浏览阅读1.4k次,点赞4次,收藏14次。废话不多说直接上干货1.js运行机制JavaScript单线程,任务需要排队执行同步任务进入主线程排队,异步任务进入事件队列排队等待被推入主线程执行定时器的延迟时间为0并不是立刻执行,只是代表相比于其他定时器更早的被执行以宏任务和微任务进一步理解js执行机制整段代码作为宏任务开始执行,执行过程中宏任务和微任务进入相应的队列中整段代码执行结束,看微任务队列中是否有任务等待执行,如果有则执行所有的微任务,直到微任务队列中的任务执行完毕,如果没有则继续执行新的宏任务执行新的宏任务,凡是在..._前端面试

linux基本概述-程序员宅基地

文章浏览阅读1k次。(3)若没有查到,则将请求发给根域DNS服务器,并依序从根域查找顶级域,由顶级查找二级域,二级域查找三级,直至找到要解析的地址或名字,即向客户机所在网络的DNS服务器发出应答信息,DNS服务器收到应答后现在缓存中存储,然后,将解析结果发给客户机。(3)若没有查到,则将请求发给根域DNS服务器,并依序从根域查找顶级域,由顶级查找二级域,二级域查找三级,直至找到要解析的地址或名字,即向客户机所在网络的DNS服务器发出应答信息,DNS服务器收到应答后现在缓存中存储,然后,将解析结果发给客户机。_linux

JavaScript学习手册十三:HTML DOM——文档元素的操作(一)_javascript学习手册十三:html dom——文档元素的操作(一)-程序员宅基地

文章浏览阅读7.9k次,点赞26次,收藏66次。HTML DOM——文档元素的操作1、通过id获取文档元素任务描述相关知识什么是DOM文档元素节点树通过id获取文档元素代码文件2、通过类名获取文档元素任务描述相关知识通过类名获取文档元素代码文件3、通过标签名获取文档元素任务描述相关知识通过标签名获取文档元素获取标签内部的子元素代码文件4、html5中获取元素的方法一任务描述相关知识css选择器querySelector的用法代码文件5、html5中获取元素的方法二任务描述相关知识querySelectorAll的用法代码文件6、节点树上的操作任务描述相关_javascript学习手册十三:html dom——文档元素的操作(一)

《LeetCode刷题》172. 阶乘后的零(java篇)_java 给定一个整数n,返回n!结果尾数中零的数量-程序员宅基地

文章浏览阅读132次。《LeetCode学习》172. 阶乘后的零(java篇)_java 给定一个整数n,返回n!结果尾数中零的数量

php 公众号消息提醒,如何开启公众号消息提醒功能-程序员宅基地

文章浏览阅读426次。请注意,本文将要给大家分享的并不是开启公众号的安全操作风险提醒,而是当公众号粉丝给公众号发消息的时候,公众号的管理员和运营者如何能在手机上立即收到消息通知,以及在手机上回复粉丝消息。第一步:授权1、在微信中点击右上角+,然后选择“添加朋友”,然后选择“公众号”,然后输入“微小助”并关注该公众号。2、进入微小助公众号,然后点击底部菜单【新增授权】,如下图所示:3、然后会打开一个温馨提示页面。请一定要..._php微信公众号服务提示

推荐文章

热门文章

相关标签