详解在SpringBoot如何优雅的使用多线程
作者:????? 发布时间:2021-07-27 13:02:39
本文带你快速了解@Async注解的用法,包括异步方法无返回值、有返回值,最后总结了@Async注解失效的几个坑。
在 SpringBoot 应用中,经常会遇到在一个接口中,同时做事情1,事情2,事情3,如果同步执行的话,则本次接口时间取决于事情1 2 3执行时间之和;如果三件事同时执行,则本次接口时间取决于事情1 2 3执行时间最长的那个,合理使用多线程,可以大大缩短接口时间。那么在 SpringBoot 应用中如何优雅的使用多线程呢?
Don't bb, show me code.
快速使用
SpringBoot应用中需要添加@EnableAsync注解,来开启异步调用,一般还会配置一个线程池,异步的方法交给特定的线程池完成,如下:
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean("doSomethingExecutor")
public Executor doSomethingExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数:线程池创建时候初始化的线程数
executor.setCorePoolSize(10);
// 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(20);
// 缓冲队列:用来缓冲执行任务的队列
executor.setQueueCapacity(500);
// 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
// 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("do-something-");
// 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程)
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.initialize();
return executor;
}
}
使用的方式非常简单,在需要异步的方法上加@Async注解
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/open/something")
public String something() {
int count = 10;
for (int i = 0; i < count; i++) {
asyncService.doSomething("index = " + i);
}
return "success";
}
}
@Slf4j
@Service
public class AsyncService {
// 指定使用beanname为doSomethingExecutor的线程池
@Async("doSomethingExecutor")
public String doSomething(String message) {
log.info("do something, message={}", message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("do something error: ", e);
}
return message;
}
}
访问:127.0.0.1:8080/open/something,日志如下
2023-02-06 23:42:42.486 INFO 21168 --- [io-8200-exec-17] x.g.b.system.controller.AsyncController : do something end, time 8 milliseconds
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-1] x.gits.boot.system.service.AsyncService : do something, message=index = 0
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-5] x.gits.boot.system.service.AsyncService : do something, message=index = 4
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-4] x.gits.boot.system.service.AsyncService : do something, message=index = 3
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-6] x.gits.boot.system.service.AsyncService : do something, message=index = 5
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-9] x.gits.boot.system.service.AsyncService : do something, message=index = 8
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-8] x.gits.boot.system.service.AsyncService : do something, message=index = 7
2023-02-06 23:42:42.488 INFO 21168 --- [do-something-10] x.gits.boot.system.service.AsyncService : do something, message=index = 9
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-7] x.gits.boot.system.service.AsyncService : do something, message=index = 6
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-2] x.gits.boot.system.service.AsyncService : do something, message=index = 1
2023-02-06 23:42:42.488 INFO 21168 --- [ do-something-3] x.gits.boot.system.service.AsyncService : do something, message=index = 2
由此可见已经达到异步执行的效果了,并且使用到了咱们配置的线程池。
获取异步方法返回值
当异步方法有返回值时,如何获取异步方法执行的返回结果呢?这时需要异步调用的方法带有返回值CompletableFuture。
CompletableFuture是对Feature的增强,Feature只能处理简单的异步任务,而CompletableFuture可以将多个异步任务进行复杂的组合。如下:
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@SneakyThrows
@ApiOperation("异步 有返回值")
@GetMapping("/open/somethings")
public String somethings() {
CompletableFuture<String> createOrder = asyncService.doSomething1("create order");
CompletableFuture<String> reduceAccount = asyncService.doSomething2("reduce account");
CompletableFuture<String> saveLog = asyncService.doSomething3("save log");
// 等待所有任务都执行完
CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join();
// 获取每个任务的返回结果
String result = createOrder.get() + reduceAccount.get() + saveLog.get();
return result;
}
}
@Slf4j
@Service
public class AsyncService {
@Async("doSomethingExecutor")
public CompletableFuture<String> doSomething1(String message) throws InterruptedException {
log.info("do something1: {}", message);
Thread.sleep(1000);
return CompletableFuture.completedFuture("do something1: " + message);
}
@Async("doSomethingExecutor")
public CompletableFuture<String> doSomething2(String message) throws InterruptedException {
log.info("do something2: {}", message);
Thread.sleep(1000);
return CompletableFuture.completedFuture("; do something2: " + message);
}
@Async("doSomethingExecutor")
public CompletableFuture<String> doSomething3(String message) throws InterruptedException {
log.info("do something3: {}", message);
Thread.sleep(1000);
return CompletableFuture.completedFuture("; do something3: " + message);
}
}
访问接口
C:\Users\Administrator>curl -X GET "http://localhost:8080/open/something" -H "accept: */*"
do something1: create order;
do something2: reduce account;
do something3: save log
控制台上关键日志如下:
2023-02-06 00:27:42.238 INFO 5672 --- [ do-something-3] x.gits.boot.system.service.AsyncService : do something3: save log
2023-02-06 00:27:42.238 INFO 5672 --- [ do-something-2] x.gits.boot.system.service.AsyncService : do something2: reduce account
2023-02-06 00:27:42.238 INFO 5672 --- [ do-something-1] x.gits.boot.system.service.AsyncService : do something1: create order
注意事项
@Async注解会在以下几个场景失效,也就是说明明使用了@Async注解,但就没有走多线程。
异步方法使用static关键词修饰;
异步类不是一个Spring容器的bean(一般使用注解@Component和@Service,并且能被Spring扫描到);
SpringBoot应用中没有添加@EnableAsync注解;
在同一个类中,一个方法调用另外一个有@Async注解的方法,注解不会生效。原因是@Async注解的方法,是在代理类中执行的。
需要注意的是: 异步方法使用注解@Async的返回值只能为void或者Future及其子类,当返回结果为其他类型时,方法还是会异步执行,但是返回值都是null,部分源码如下:
AsyncExecutionInterceptor#invoke
通过上边几个示例,@Async实际还是通过Future或CompletableFuture来异步执行的,Spring又封装了一下,让我们使用的更方便。
来源:https://blog.csdn.net/manhengwei/article/details/128835352
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 爬取过程:你好,李焕英 短评的URL:https://movie.douban.com/subject/34841067/comments?
- Python是一种解释型、面向对象、动态数据类型的高级程序设计语言,本文就举一例Python类继承的实例。实例代码如下:#! /usr/bi
- Linux Journal 发表了一篇优化 Oracle 数据库的文章,感觉十分的有用。简要介绍其摘要和大家共同分享 Linux 在企业级数
- 概念softmax函数是常用的输出层函数,常用来解决互斥标签的多分类问题。当然由于他是非线性函数,也可以作为隐藏层函数使用反向传播求导可以看
- 本文实例讲述了python中尾递归用法。分享给大家供大家参考。具体分析如下:如果一个函数中所有递归形式的调用都出现在函数的末尾,我们称这个递
- 前言有时候大家需要知道一个关键词在互联网上的热度,想知道某个关键词的热度变化趋势。大家可能就是使用百度指数、微信指数之类的。非常好用,但是就
- 注:此处“重复”非完全重复,意为某字段数据重复HZT表结构IDintTitlenvarchar(50)AddDatedatetime数据一.
- 常用 ASCII 码表对照表:注意如下几点:0-9:48-57A-Z:65-90a-z:97-122ord()函数介绍: ord(
- Pycharm实然提示过期了,网上找了很多Pycharm激活码,要么只支持老版本,要么是不能用。费了半天时间终于在一公众号里找到一枚可以使用
- 本文以修改用户名密码单元为案例,编写测试脚本。完成修改用户名密码模块单元测试。(ps.这个demo中登陆密码为“admin”)1. 打开浏览
- 效果基于Python3。在自己写小工具的时候因为这个功能纠结了一会儿,这里写个小例子,供有需要的参考。小例子,就是点击按钮打开路径选择窗口,
- 本文实例讲述了Python实现获取汉字偏旁部首的方法。分享给大家供大家参考,具体如下:功能介绍传入一个汉字,返回其偏旁部首字典分为本地字典与
- 0. 前言数据处理过程中,可视化可以更直观得感受数据,因此打算结合自己的一些实践经理,以效果为准写这篇博客。内容应该会不断扩充。1. mat
- php 如何获取请求的xml数据,对方通过http协议post提交过来xml数据,php如何获取到这些数据呢?<?php $xml_d
- 素数(prime number)也叫质数,为大于1的且除1和本身以外不再有其他因数的自然数,与之相对的是合数,素数有无限个。计算小于N的素数
- 列表的添加1)+ 添加2)append 追加一次只能添加一个元素到列表中,适合用于循环里3)extend 拉伸可一次添加多个元素到列表中4)
- 在数据处理过程中比如从CSV文件中导入数据data_df = pd.read_csv("names.csv")在处理之前
- 此文章主要介绍的是MySQL数据库的字符(串)的实际操作步骤,我们大家都知道MySQL数据库的字符(串)在实际操作是经常被用到了,所以你对其
- 我的读者知道我是一个喜欢痛骂Python3 unicode的人。这次也不例外。我将会告诉你用unicode有多痛苦和为什么我不能闭嘴。我花了
- 我认为多选列表具有完美的功能——只需按下Ctrl键,同时点击鼠标从列表中选择多个项目。以下是一个典型的多选列表框:选出你最喜爱的快餐:&nb