網(wǎng)站首頁 編程語言 正文
本文帶你快速了解@Async注解的用法,包括異步方法無返回值、有返回值,最后總結(jié)了@Async注解失效的幾個(gè)坑。
在 SpringBoot 應(yīng)用中,經(jīng)常會遇到在一個(gè)接口中,同時(shí)做事情1,事情2,事情3,如果同步執(zhí)行的話,則本次接口時(shí)間取決于事情1 2 3執(zhí)行時(shí)間之和;如果三件事同時(shí)執(zhí)行,則本次接口時(shí)間取決于事情1 2 3執(zhí)行時(shí)間最長的那個(gè),合理使用多線程,可以大大縮短接口時(shí)間。那么在 SpringBoot 應(yīng)用中如何優(yōu)雅的使用多線程呢?
Don't bb, show me code.
快速使用?
SpringBoot應(yīng)用中需要添加@EnableAsync注解,來開啟異步調(diào)用,一般還會配置一個(gè)線程池,異步的方法交給特定的線程池完成,如下:
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean("doSomethingExecutor")
public Executor doSomethingExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心線程數(shù):線程池創(chuàng)建時(shí)候初始化的線程數(shù)
executor.setCorePoolSize(10);
// 最大線程數(shù):線程池最大的線程數(shù),只有在緩沖隊(duì)列滿了之后才會申請超過核心線程數(shù)的線程
executor.setMaxPoolSize(20);
// 緩沖隊(duì)列:用來緩沖執(zhí)行任務(wù)的隊(duì)列
executor.setQueueCapacity(500);
// 允許線程的空閑時(shí)間60秒:當(dāng)超過了核心線程之外的線程在空閑時(shí)間到達(dá)之后會被銷毀
executor.setKeepAliveSeconds(60);
// 線程池名的前綴:設(shè)置好了之后可以方便我們定位處理任務(wù)所在的線程池
executor.setThreadNamePrefix("do-something-");
// 緩沖隊(duì)列滿了之后的拒絕策略:由調(diào)用線程處理(一般是主線程)
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
由此可見已經(jīng)達(dá)到異步執(zhí)行的效果了,并且使用到了咱們配置的線程池。?
獲取異步方法返回值?
當(dāng)異步方法有返回值時(shí),如何獲取異步方法執(zhí)行的返回結(jié)果呢?這時(shí)需要異步調(diào)用的方法帶有返回值CompletableFuture。
CompletableFuture是對Feature的增強(qiáng),F(xiàn)eature只能處理簡單的異步任務(wù),而CompletableFuture可以將多個(gè)異步任務(wù)進(jìn)行復(fù)雜的組合。如下:
@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");
// 等待所有任務(wù)都執(zhí)行完
CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join();
// 獲取每個(gè)任務(wù)的返回結(jié)果
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
控制臺上關(guān)鍵日志如下:?
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
注意事項(xiàng)?
@Async注解會在以下幾個(gè)場景失效,也就是說明明使用了@Async注解,但就沒有走多線程。
- 異步方法使用static關(guān)鍵詞修飾;
- 異步類不是一個(gè)Spring容器的bean(一般使用注解@Component和@Service,并且能被Spring掃描到);
- SpringBoot應(yīng)用中沒有添加@EnableAsync注解;
- 在同一個(gè)類中,一個(gè)方法調(diào)用另外一個(gè)有@Async注解的方法,注解不會生效。原因是@Async注解的方法,是在代理類中執(zhí)行的。
需要注意的是: 異步方法使用注解@Async的返回值只能為void或者Future及其子類,當(dāng)返回結(jié)果為其他類型時(shí),方法還是會異步執(zhí)行,但是返回值都是null,部分源碼如下:
AsyncExecutionInterceptor#invoke
通過上邊幾個(gè)示例,@Async實(shí)際還是通過Future或CompletableFuture來異步執(zhí)行的,Spring又封裝了一下,讓我們使用的更方便。?
原文鏈接:https://blog.csdn.net/manhengwei/article/details/128835352
相關(guān)推薦
- 2022-05-22 SQL?Server數(shù)據(jù)庫基本概念、組成、常用對象與約束_MsSql
- 2023-04-26 C語言形參與實(shí)參使用的差別講解_C 語言
- 2022-09-05 python使用pip成功導(dǎo)入庫后還是報(bào)錯(cuò)的解決方法(針對vscode)_python
- 2022-12-23 Kotlin擴(kuò)展函數(shù)與運(yùn)算符重載超詳細(xì)解析_Android
- 2022-04-04 webpack-plugins: plugin的使用 clean-webpack-plugin Cl
- 2022-05-12 Android Studio 崩潰一閃而過抓不到日志
- 2022-09-21 Python安裝和配置uWSGI的詳細(xì)過程_python
- 2023-06-20 Jupyter?Notebook中%time和%timeit的使用詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支