当前位置: 首页 > news >正文

Spring Boot实践五 --异步任务线程池

一、使用@Async实现异步调用

在Spring Boot中,我们只需要通过使用@Async注解就能简单的将原来的同步函数变为异步函数,Task类实现如下:

package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Component
public class AsyncTasks {public static Random random = new Random();@Asyncpublic CompletableFuture<String> doTaskOne() throws Exception {log.info("开始做任务一");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务一,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务一完成");}@Asyncpublic CompletableFuture<String> doTaskTwo() throws Exception {log.info("开始做任务二");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务二,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务二完成");}@Asyncpublic CompletableFuture<String>  doTaskThree() throws Exception {log.info("开始做任务三");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务三,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务三完成");}
}

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

为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

package com.example.demospringboot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;@EnableAsync
@SpringBootApplication
public class DemospringbootApplication {public static void main(String[] args) {SpringApplication.run(DemospringbootApplication.class, args);}}

测试类如下:

package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.cache.CacheManager;@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemospringbootApplicationTests {@Autowiredprivate AsyncTasks asyncTasks;@Testpublic void test() throws Exception {asyncTasks.doTaskOne();asyncTasks.doTaskTwo();asyncTasks.doTaskThree();}}

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

2023-08-01 21:32:46.064  INFO 1764 --- [         task-1] com.example.demospringboot.AsyncTasks    : 开始做任务一
2023-08-01 21:32:46.064  INFO 1764 --- [         task-3] com.example.demospringboot.AsyncTasks    : 开始做任务三
2023-08-01 21:32:46.064  INFO 1764 --- [         task-2] com.example.demospringboot.AsyncTasks    : 开始做任务二

异步回调

那么我们如何判断上述三个异步调用是否已经执行完成呢?我们需要使用CompletableFuture来返回异步调用的结果,就像如下方式改造doTaskOne函数:

package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;import java.util.Random;
import java.util.concurrent.CompletableFuture;@Slf4j
@Component
public class AsyncTasks {public static Random random = new Random();@Asyncpublic CompletableFuture<String> doTaskOne() throws Exception {log.info("开始做任务一");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务一,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务一完成");}@Asyncpublic CompletableFuture<String> doTaskTwo() throws Exception {log.info("开始做任务二");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务二,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务二完成");}@Asyncpublic CompletableFuture<String>  doTaskThree() throws Exception {log.info("开始做任务三");long start = System.currentTimeMillis();Thread.sleep(random.nextInt(10000));long end = System.currentTimeMillis();log.info("完成任务三,耗时:" + (end - start) + "毫秒");return CompletableFuture.completedFuture("任务三完成");}}

下面我们改造一下测试用例,让测试在等待完成三个异步调用之后来做一些其他事情

package com.example.demospringboot;import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CompletableFuture;@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemospringbootApplicationTests {@Autowiredprivate AsyncTasks asyncTasks;@Testpublic void test() throws Exception {long start = System.currentTimeMillis();CompletableFuture<String> task1 = asyncTasks.doTaskOne();CompletableFuture<String> task2 = asyncTasks.doTaskTwo();CompletableFuture<String> task3 = asyncTasks.doTaskThree();CompletableFuture.allOf(task1, task2, task3).join();long end = System.currentTimeMillis();log.info("任务全部完成,总耗时:" + (end - start) + "毫秒");}}

执行一下上述的单元测试,可以看到如下结果:

2023-08-01 21:41:40.347  INFO 13684 --- [         task-1] com.example.demospringboot.AsyncTasks    : 开始做任务一
2023-08-01 21:41:40.347  INFO 13684 --- [         task-3] com.example.demospringboot.AsyncTasks    : 开始做任务三
2023-08-01 21:41:40.347  INFO 13684 --- [         task-2] com.example.demospringboot.AsyncTasks    : 开始做任务二
2023-08-01 21:41:44.817  INFO 13684 --- [         task-2] com.example.demospringboot.AsyncTasks    : 完成任务二,耗时:4470毫秒
2023-08-01 21:41:45.042  INFO 13684 --- [         task-1] com.example.demospringboot.AsyncTasks    : 完成任务一,耗时:4695毫秒
2023-08-01 21:41:48.154  INFO 13684 --- [         task-3] com.example.demospringboot.AsyncTasks    : 完成任务三,耗时:7807毫秒
2023-08-01 21:41:48.154  INFO 13684 --- [           main] c.e.d.DemospringbootApplicationTests     : 任务全部完成,总耗时:7817毫秒

可以看到,通过异步调用,让任务一、二、三并发执行,有效的减少了程序的总运行时间。

参考:https://blog.didispace.com/spring-boot-learning-2-7-5/

http://www.lryc.cn/news/105046.html

相关文章:

  • <C语言> 动态内存管理
  • 【ASPICE】:学习记录
  • 图论--最短路问题
  • go 结构体 - 值类型、引用类型 - 结构体转json类型 - 指针类型的种类 - 结构体方法 - 继承 - 多态(interface接口) - 练习
  • 盘点16个.Net开源项目
  • 记录对 require.js 的理解
  • minio-分布式文件存储系统
  • Kindling the Darkness: A Practical Low-light Image Enhancer论文阅读笔记
  • AcWing 4575. Bi数和Phi数
  • 《Federated Unlearning via Active Forgetting》论文精读
  • Java课题笔记~Maven基础知识
  • xcode中如何显示文件后缀
  • SpringBoot使用JKS或PKCS12证书实现https
  • 云原生势不可挡,如何跳离云原生深水区?
  • python的decimal或者叫Decimal,BigDecimal
  • Mac环境变量问题
  • Shell脚本学习-Web服务监控
  • 【ChatGPT】基于WSL+Docker的ChatGPT PLUS共享服务部署
  • 【论文阅读24】Better Few-Shot Text Classification with Pre-trained Language Model
  • 119、Spring容器启动流程是怎样的(配有Spring启动完整流程图)
  • 微信公众号开发学习
  • 【LeetCode】221.最大正方形
  • 生成模型相关算法:EM算法步骤和公式推导
  • Compose手势
  • 【雕爷学编程】Arduino动手做(177)---ESP-32 掌控板2
  • Ubuntu-文件和目录相关命令
  • 显式接口实现(C# 编程指南)
  • element-ui 图片上传 及 quillEditor富文本(图片视频上传)
  • 前端技术Vue学习笔记--002
  • 【RabbitMQ(day4)】SpringBoot整合RabbitMQ与MQ应用场景说明