Springboot使用異步方法優(yōu)化Service邏輯,提高接口響應(yīng)速度方式
使用異步方法優(yōu)化Service邏輯,提高接口響應(yīng)速度
一、業(yè)務(wù)場景
例如生成驗證碼和發(fā)送驗證碼組成的業(yè)務(wù),其實無需等到真正發(fā)送成功驗證碼才對客戶端進行響應(yīng),可以讓短信發(fā)送者一個耗時操作轉(zhuǎn)為異步執(zhí)行
二、異步任務(wù)在springboot的使用
@RestController
public class AsyncArticleController {
@Autowired
private ArticleService articleService;
/**
* 模擬獲取文章后閱讀量+1
*/
@PostMapping("/article")
public String getArticle() {
// 查詢文章
String article = articleService.selectArticle();
// 閱讀量+1
articleService.updateReadCount();
System.out.println("getArticle文章閱讀業(yè)務(wù)執(zhí)行完畢");
return article;
}
}
@Service
public class ArticleService {
// 查詢文章
public String selectArticle() {
// TODO 模擬文章查詢操作
System.out.println("查詢?nèi)蝿?wù)線程,線程名:"+Thread.currentThread().getName());
return "文章詳情";
}
// 文章閱讀量+1
@Async
public void updateReadCount() {
// TODO 模擬耗時操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
}
}
@SpringBootApplication
@EnableAsync
public class SpringbootRunnerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRunnerApplication.class, args);
}
}

注意:
@EnableAsync // 使用異步方法時需要提前開啟(在啟動類上或配置類上) @Async // 被async注解修飾的方法由SpringBoot默認(rèn)線程池(SimpleAsyncTaskExecutor)執(zhí)行
三、自定義線程池執(zhí)行異步方法
第一步配置自定義線程池
package com.hl.springbootrunner.asyncdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@EnableAsync // 開啟多線程, 項目啟動時自動創(chuàng)建
@Configuration
public class AsyncConfig {
@Bean("readCountExecutor") //指定自定義線程池名稱
public ThreadPoolTaskExecutor asyncOperationExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 設(shè)置核心線程數(shù)
executor.setCorePoolSize(8);
// 設(shè)置最大線程數(shù)
executor.setMaxPoolSize(20);
// 設(shè)置隊列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
// 設(shè)置線程活躍時間(秒)
executor.setKeepAliveSeconds(60);
// 設(shè)置線程名前綴+分組名稱
executor.setThreadNamePrefix("AsyncOperationThread-");
executor.setThreadGroupName("AsyncOperationGroup");
// 所有任務(wù)結(jié)束后關(guān)閉線程池
executor.setWaitForTasksToCompleteOnShutdown(true);
// 初始化
executor.initialize();
return executor;
}
}
第二步, 在@Async注解上指定執(zhí)行的線程池,ArticleService中指定執(zhí)行的線程池
// 文章閱讀量+1,指定線程池
@Async("readCountExecutor")
public void updateReadCountByExecutor() {
// TODO 模擬耗時操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
}
第三步,在AsyncArcicleController中
/**
* 模擬獲取文章后閱讀量+1,指定線程池
*/
@PostMapping("/articleByExecutor")
public String getArticleByExecutor() {
// 查詢文章
String article = articleService.selectArticle();
// 閱讀量+1
articleService.updateReadCountByExecutor();
System.out.println("getArticleByExecutor文章閱讀業(yè)務(wù)執(zhí)行完畢");
return article;
}

四、捕獲(無返回值的)異步方法中的異常
自定義異常處理類CustomAsyncExceptionHandler
@Component
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
System.out.println("異常捕獲---------------------------------");
System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (Object param : obj) {
System.out.println("Parameter value - " + param);
}
System.out.println("異常捕獲---------------------------------");
}
}
@Async("readCountExecutor")
public void updateReadCountNoReturnByExecutor() {
// TODO 模擬耗時操作
try {
Thread.sleep(3000);
int i = 1/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
}

五、捕獲(有返回值)異步方法中的異常
使用Future類及其子類來接收異步方法返回值
// 文章閱讀量+1
@Async("readCountExecutor")
public CompletableFuture<Integer> updateReadCountHasResult() {
// TODO 模擬耗時操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("更新文章閱讀量線程"+Thread.currentThread().getName());
return CompletableFuture.completedFuture(100 + 1);
}
@GetMapping("/articleCompletableFuture")
public String getArticleCompletableFuture() throws ExecutionException, InterruptedException {
// 查詢文章
String article = articleService.selectArticle();
// 閱讀量+1
CompletableFuture<Integer> future = articleService.updateReadCountHasResult();
//無返回值的異步方法拋出異常不會影響Controller的主要業(yè)務(wù)邏輯
//有返回值的異步方法拋出異常會影響Controller的主要業(yè)務(wù)邏輯
int count = 0;
// 循環(huán)等待異步請求結(jié)果
while (true) {
if(future.isCancelled()) {
System.out.println("異步任務(wù)取消");
break;
}
if (future.isDone()) {
count = future.get();
System.out.println(count);
break;
}
}
System.out.println("getArticleCompletableFuture文章閱讀業(yè)務(wù)執(zhí)行完畢");
return article + count;
}

注意:
- 無返回值的異步方法拋出異常不會影響Controller的主要業(yè)務(wù)邏輯
- 有返回值的異步方法拋出異常會影響Controller的主要業(yè)務(wù)邏輯
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
攔截Druid數(shù)據(jù)源自動注入帳密解密實現(xiàn)詳解
這篇文章主要為大家介紹了攔截Druid數(shù)據(jù)源自動注入帳密解密實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
解決swagger2中@ApiResponse的response不起作用
這篇文章主要介紹了解決swagger2中@ApiResponse的response不起作用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot+RabbitMQ+Redis實現(xiàn)商品秒殺的示例代碼
本文主要介紹了SpringBoot+RabbitMQ+Redis實現(xiàn)商品秒殺,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
使用Mybatis遇到的坑之Integer類型參數(shù)的解讀
這篇文章主要介紹了使用Mybatis遇到的坑之Integer類型參數(shù)的解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Java異常繼承結(jié)構(gòu)解析_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了Java異常繼承結(jié)構(gòu)解析的相關(guān)知識,需要的朋友可以參考下2017-04-04

