欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot如何優(yōu)雅的使用多線程實(shí)例詳解

 更新時(shí)間:2020年05月29日 08:43:18   作者:讀釣  
這篇文章主要給大家介紹了關(guān)于Spring Boot如何優(yōu)雅的使用多線程的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

本文帶你快速了解@Async注解的用法,包括異步方法無(wú)返回值、有返回值,最后總結(jié)了@Async注解失效的幾個(gè)坑。

在 SpringBoot 應(yīng)用中,經(jīng)常會(huì)遇到在一個(gè)接口中,同時(shí)做事情1,事情2,事情3,如果同步執(zhí)行的話,則本次接口時(shí)間取決于事情1 2 3執(zhí)行時(shí)間之和;如果三件事同時(shí)執(zhí)行,則本次接口時(shí)間取決于事情1 2 3執(zhí)行時(shí)間最長(zhǎng)的那個(gè),合理使用多線程,可以大大縮短接口時(shí)間。那么在 SpringBoot 應(yīng)用中如何優(yōu)雅的使用多線程呢?

Don't bb, show me code.

快速使用

SpringBoot應(yīng)用中需要添加@EnableAsync注解,來(lái)開(kāi)啟異步調(diào)用,一般還會(huì)配置一個(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ì)列滿了之后才會(huì)申請(qǐng)超過(guò)核心線程數(shù)的線程
  executor.setMaxPoolSize(20);
  // 緩沖隊(duì)列:用來(lái)緩沖執(zhí)行任務(wù)的隊(duì)列
  executor.setQueueCapacity(500);
  // 允許線程的空閑時(shí)間60秒:當(dāng)超過(guò)了核心線程之外的線程在空閑時(shí)間到達(dá)之后會(huì)被銷(xiāo)毀
  executor.setKeepAliveSeconds(60);
  // 線程池名的前綴:設(shè)置好了之后可以方便我們定位處理任務(wù)所在的線程池
  executor.setThreadNamePrefix("do-something-");
  // 緩沖隊(duì)列滿了之后的拒絕策略:由調(diào)用線程處理(一般是主線程)
  executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
  executor.initialize();
  return executor;
 }
}

使用的方式非常簡(jiǎn)單,在需要異步的方法上加@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;
 }
}

訪問(wèn):127.0.0.1:8080/open/something,日志如下

2020-04-19 23:42:42.486  INFO 21168 --- [io-8200-exec-17] x.g.b.system.controller.AsyncController  : do something end, time 8 milliseconds
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-1] x.gits.boot.system.service.AsyncService  : do something, message=index = 0
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-5] x.gits.boot.system.service.AsyncService  : do something, message=index = 4
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-4] x.gits.boot.system.service.AsyncService  : do something, message=index = 3
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-6] x.gits.boot.system.service.AsyncService  : do something, message=index = 5
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-9] x.gits.boot.system.service.AsyncService  : do something, message=index = 8
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-8] x.gits.boot.system.service.AsyncService  : do something, message=index = 7
2020-04-19 23:42:42.488  INFO 21168 --- [do-something-10] x.gits.boot.system.service.AsyncService  : do something, message=index = 9
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-7] x.gits.boot.system.service.AsyncService  : do something, message=index = 6
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-2] x.gits.boot.system.service.AsyncService  : do something, message=index = 1
2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-3] x.gits.boot.system.service.AsyncService  : do something, message=index = 2

由此可見(jiàn)已經(jīng)達(dá)到異步執(zhí)行的效果了,并且使用到了咱們配置的線程池。

獲取異步方法返回值

當(dāng)異步方法有返回值時(shí),如何獲取異步方法執(zhí)行的返回結(jié)果呢?這時(shí)需要異步調(diào)用的方法帶有返回值CompletableFuture。

CompletableFuture是對(duì)Feature的增強(qiáng),F(xiàn)eature只能處理簡(jiǎn)單的異步任務(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);
 }
}

訪問(wèn)接口

C:\Users\Administrator>curl -X GET "http://localhost:8200/open/somethings" -H "accept: */*"
do something1: create order; do something2: reduce account; do something3: save log

控制臺(tái)上關(guān)鍵日志如下:

2020-04-20 00:27:42.238  INFO 5672 --- [ do-something-3] x.gits.boot.system.service.AsyncService  : do something3: save log
2020-04-20 00:27:42.238  INFO 5672 --- [ do-something-2] x.gits.boot.system.service.AsyncService  : do something2: reduce account
2020-04-20 00:27:42.238  INFO 5672 --- [ do-something-1] x.gits.boot.system.service.AsyncService  : do something1: create order

注意事項(xiàng)

@Async注解會(huì)在以下幾個(gè)場(chǎng)景失效,也就是說(shuō)明明使用了@Async注解,但就沒(méi)有走多線程。

  • 異步方法使用static關(guān)鍵詞修飾;
  • 異步類(lèi)不是一個(gè)Spring容器的bean(一般使用注解@Component和@Service,并且能被Spring掃描到);
  • SpringBoot應(yīng)用中沒(méi)有添加@EnableAsync注解;
  • 在同一個(gè)類(lèi)中,一個(gè)方法調(diào)用另外一個(gè)有@Async注解的方法,注解不會(huì)生效。原因是@Async注解的方法,是在代理類(lèi)中執(zhí)行的。

需要注意的是:

異步方法使用注解@Async的返回值只能為void或者Future及其子類(lèi),當(dāng)返回結(jié)果為其他類(lèi)型時(shí),方法還是會(huì)異步執(zhí)行,但是返回值都是null,部分源碼如下:

AsyncExecutionInterceptor#invoke

通過(guò)上邊幾個(gè)示例,@Async實(shí)際還是通過(guò)Future或CompletableFuture來(lái)異步執(zhí)行的,Spring又封裝了一下,讓我們使用的更方便。

本文示例代碼:gitee.com/songyinyin/… ,搜索AsyncController可得。

總結(jié)

到此這篇關(guān)于Spring Boot如何優(yōu)雅的使用多線程的文章就介紹到這了,更多相關(guān)Spring Boot優(yōu)雅使用多線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot如何使用Undertow做服務(wù)器

    SpringBoot如何使用Undertow做服務(wù)器

    這篇文章主要介紹了SpringBoot如何使用Undertow做服務(wù)器,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Spring整合JPA與Hibernate流程詳解

    Spring整合JPA與Hibernate流程詳解

    這篇文章主要介紹了Spring整合Hibernate與JPA,在正式進(jìn)入Hibernate的高級(jí)應(yīng)用之前,需要了解聲明是數(shù)據(jù)模型與領(lǐng)域模型,這兩個(gè)概念將會(huì)幫助我們更好的理解實(shí)體對(duì)象的關(guān)聯(lián)關(guān)系映射
    2023-01-01
  • SpringMVC用JsonSerialize日期轉(zhuǎn)換方法

    SpringMVC用JsonSerialize日期轉(zhuǎn)換方法

    下面小編就為大家?guī)?lái)一篇SpringMVC用JsonSerialize日期轉(zhuǎn)換方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起 小編過(guò)來(lái)看看吧
    2016-11-11
  • Java中final關(guān)鍵字的使用與注意總結(jié)

    Java中final關(guān)鍵字的使用與注意總結(jié)

    這篇文章主要給大家介紹了關(guān)于Java中final關(guān)鍵字的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • 不寫(xiě)mybatis的@Param有的報(bào)錯(cuò)有的卻不報(bào)錯(cuò)問(wèn)題分析

    不寫(xiě)mybatis的@Param有的報(bào)錯(cuò)有的卻不報(bào)錯(cuò)問(wèn)題分析

    這篇文章主要為大家介紹了不寫(xiě)mybatis的@Param有的報(bào)錯(cuò)有的卻不報(bào)錯(cuò)問(wèn)題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • spring boot教程之產(chǎn)生的背景及其優(yōu)勢(shì)

    spring boot教程之產(chǎn)生的背景及其優(yōu)勢(shì)

    這篇文章主要介紹了spring boot教程之產(chǎn)生的背景及其優(yōu)勢(shì)的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • Java Hibernate中的持久化類(lèi)和實(shí)體類(lèi)關(guān)系

    Java Hibernate中的持久化類(lèi)和實(shí)體類(lèi)關(guān)系

    Hibernate是一種Java對(duì)象關(guān)系映射框架,通過(guò)持久化類(lèi)將Java對(duì)象映射到數(shù)據(jù)庫(kù)表中。持久化類(lèi)需要實(shí)現(xiàn)無(wú)參構(gòu)造器、具有標(biāo)識(shí)屬性和使用注解或XML進(jìn)行映射。Hibernate通過(guò)Session來(lái)管理對(duì)象的狀態(tài),包括臨時(shí)狀態(tài)、持久化狀態(tài)和游離狀態(tài)
    2023-04-04
  • Swing常用組件之文本框和文本區(qū)

    Swing常用組件之文本框和文本區(qū)

    這篇文章主要為大家詳細(xì)介紹了Swing常用組件之文本框(JTestField)和文本區(qū)(JTextArea),Swing是一個(gè)用于開(kāi)發(fā)Java應(yīng)用程序用戶界面的開(kāi)發(fā)工具包,本文開(kāi)始帶大家學(xué)習(xí)Swing
    2016-05-05
  • mybatis-plus如何配置自定義數(shù)據(jù)類(lèi)型TypeHandle

    mybatis-plus如何配置自定義數(shù)據(jù)類(lèi)型TypeHandle

    這篇文章主要介紹了mybatis-plus如何配置自定義數(shù)據(jù)類(lèi)型TypeHandle,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java中的WeakHashMap簡(jiǎn)析

    Java中的WeakHashMap簡(jiǎn)析

    這篇文章主要介紹了Java中的WeakHashMap簡(jiǎn)析,Map 的子類(lèi)常見(jiàn)的有 HashMap、Hashtable、ConcurrentHashMap、LinkedHashMap 等,WeakHashMap,直譯就是,虛弱的 HashMap,從名字可得知其和 HashMap 有關(guān),需要的朋友可以參考下
    2023-09-09

最新評(píng)論