[線程池]Springboot如何使用線程池

來源:騰訊云

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

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

Don"t bb, show me code.


(相關(guān)資料圖)

快速使用

SpringBoot應(yīng)用中需要添加@EnableAsync注解,來開啟異步調(diào)用,一般還會配置一個線程池,異步的方法交給特定的線程池完成,如下:

@Configuration@EnableAsyncpublic class AsyncConfiguration {    @Bean("doSomethingExecutor")    public Executor doSomethingExecutor() {        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        // 核心線程數(shù):線程池創(chuàng)建時候初始化的線程數(shù)        executor.setCorePoolSize(10);        // 最大線程數(shù):線程池最大的線程數(shù),只有在緩沖隊列滿了之后才會申請超過核心線程數(shù)的線程        executor.setMaxPoolSize(20);        // 緩沖隊列:用來緩沖執(zhí)行任務(wù)的隊列        executor.setQueueCapacity(500);        // 允許線程的空閑時間60秒:當(dāng)超過了核心線程之外的線程在空閑時間到達之后會被銷毀        executor.setKeepAliveSeconds(60);        // 線程池名的前綴:設(shè)置好了之后可以方便我們定位處理任務(wù)所在的線程池        executor.setThreadNamePrefix("do-something-");        // 緩沖隊列滿了之后的拒絕策略:由調(diào)用線程處理(一般是主線程)        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());        executor.initialize();        return executor;    }}

使用的方式非常簡單,在需要異步的方法上加@Async注解

@RestControllerpublic 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);        }        lon        return "success";    }}@Slf4j@Servicepublic 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,日志如下

2020-04-19 23:42:42.486  INFO 21168 --- [io-8200-exec-17] x.g.b.system.controller.AsyncController  : do something end, time 8 milliseconds2020-04-19 23:42:42.488  INFO 21168 --- [ do-something-1] x.gits.boot.system.service.AsyncService  : do something, message=index = 02020-04-19 23:42:42.488  INFO 21168 --- [ do-something-5] x.gits.boot.system.service.AsyncService  : do something, message=index = 42020-04-19 23:42:42.488  INFO 21168 --- [ do-something-4] x.gits.boot.system.service.AsyncService  : do something, message=index = 32020-04-19 23:42:42.488  INFO 21168 --- [ do-something-6] x.gits.boot.system.service.AsyncService  : do something, message=index = 52020-04-19 23:42:42.488  INFO 21168 --- [ do-something-9] x.gits.boot.system.service.AsyncService  : do something, message=index = 82020-04-19 23:42:42.488  INFO 21168 --- [ do-something-8] x.gits.boot.system.service.AsyncService  : do something, message=index = 72020-04-19 23:42:42.488  INFO 21168 --- [do-something-10] x.gits.boot.system.service.AsyncService  : do something, message=index = 92020-04-19 23:42:42.488  INFO 21168 --- [ do-something-7] x.gits.boot.system.service.AsyncService  : do something, message=index = 62020-04-19 23:42:42.488  INFO 21168 --- [ do-something-2] x.gits.boot.system.service.AsyncService  : do something, message=index = 12020-04-19 23:42:42.488  INFO 21168 --- [ do-something-3] x.gits.boot.system.service.AsyncService  : do something, message=index = 2

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

獲取異步方法返回值

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

CompletableFuture是對Feature的增強,F(xiàn)eature只能處理簡單的異步任務(wù),而CompletableFuture可以將多個異步任務(wù)進行復(fù)雜的組合。如下:

@RestControllerpublic class AsyncController {    @Autowired    private AsyncService asyncService;    @SneakyThrows    @ApiOperation("異步 有返回值")    @GetMapping("/open/somethings")    public String somethings() {        CompletableFuture createOrder = asyncService.doSomething1("create order");        CompletableFuture reduceAccount = asyncService.doSomething2("reduce account");        CompletableFuture saveLog = asyncService.doSomething3("save log");        // 等待所有任務(wù)都執(zhí)行完        CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join();        // 獲取每個任務(wù)的返回結(jié)果        String result = createOrder.get() + reduceAccount.get() + saveLog.get();        return result;    }}@Slf4j@Servicepublic class AsyncService {    @Async("doSomethingExecutor")    public CompletableFuture doSomething1(String message) throws InterruptedException {        log.info("do something1: {}", message);        Thread.sleep(1000);        return CompletableFuture.completedFuture("do something1: " + message);    }    @Async("doSomethingExecutor")    public CompletableFuture doSomething2(String message) throws InterruptedException {        log.info("do something2: {}", message);        Thread.sleep(1000);        return CompletableFuture.completedFuture("; do something2: " + message);    }    @Async("doSomethingExecutor")    public CompletableFuture 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:8200/open/somethings" -H "accept: */*"do something1: create order; do something2: reduce account; do something3: save log

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

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

注意事項

@Async注解會在以下幾個場景失效,也就是說明明使用了@Async注解,但就沒有走多線程。

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

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

標(biāo)簽:

推薦

財富更多》

動態(tài)更多》

熱點