Springboot實(shí)現(xiàn)異步任務(wù)線程池代碼實(shí)例
異步任務(wù)線程池
異步任務(wù)線程池是一種用于處理異步任務(wù)的機(jī)制,它可以提高程序的并發(fā)性能和響應(yīng)速度。
通過將任務(wù)提交給線程池,線程池會(huì)自動(dòng)管理線程的創(chuàng)建和銷毀,從而避免了頻繁創(chuàng)建和銷毀線程的開銷。
同時(shí),線程池還可以控制并發(fā)線程的數(shù)量,避免資源過度占用。
異步任務(wù)線程池是多線程編程中常用的一種技術(shù),它可以應(yīng)用于各種場(chǎng)景,如網(wǎng)絡(luò)請(qǐng)求、數(shù)據(jù)庫(kù)操作、文件處理等。
1. 啟動(dòng)類添加@EnableAsync注解
package com.gblfy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class JavaEscapeApplication {
public static void main(String[] args) {
SpringApplication.run(JavaEscapeApplication.class, args);
}
}
2. 異步方法添加@Async注解
package com.gblfy.async_task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Slf4j
@Service
public class AsyncService {
@Async
public void asyncProcess01() throws Exception {
log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName());
Thread.sleep(2000);
log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName());
}
@Async
public Future<String> asyncProcess02() throws Exception {
log.info("AsyncService Start to asyncProcess02->{}", Thread.currentThread().getName());
Thread.sleep(2000);
log.info("AsyncService Done to asyncProcess02->{}", Thread.currentThread().getName());
return new AsyncResult<>("imooc");
}
@Async
public void asyncProcess03() {
log.info("AsyncService Start to asyncProcess03->{}", Thread.currentThread().getName());
throw new RuntimeException("throw exception asyncProcess03");
}
}
3. 自定義線程池以及線程池異常策略
package com.gblfy.async_task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 自定義異步任務(wù)線程池
*/
@Slf4j
@Configuration
public class AsyncTaskConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("cmiip-");
executor.setCorePoolSize(15);
executor.setMaxPoolSize(20);
executor.setKeepAliveSeconds(5);
executor.setQueueCapacity(100);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
// 報(bào)警郵件,發(fā)短信等等
log.error("async task some Error: {} ,{} , {}", ex.getMessage(),
method.getDeclaringClass().getName() + "." + method.getName(),
Arrays.toString(params));
}
};
}
}
測(cè)試
package com.gblfy.async_task;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@Slf4j
@SpringBootTest
class AsyncServiceTest {
@Autowired
private AsyncService asyncService;
@Test
void contextLoads() throws Exception {
// asyncService.asyncProcess01();
Future<String> future= asyncService.asyncProcess02();
log.info("Async Process02 return :->{}", future.get(1, TimeUnit.SECONDS));
}
@Test
void contextLoads2() throws Exception {
asyncService.asyncProcess03();
Thread.sleep(3000);
}
}
到此這篇關(guān)于Springboot實(shí)現(xiàn)異步任務(wù)線程池代碼實(shí)例的文章就介紹到這了,更多相關(guān)Springboot異步任務(wù)線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis-flex與springBoot整合的實(shí)現(xiàn)示例
Mybatis-flex提供了簡(jiǎn)單易用的API,開發(fā)者只需要簡(jiǎn)單的配置即可使用,本文主要介紹了mybatis-flex與springBoot整合,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
MyBatis批量插入的五種方式小結(jié)(MyBatis以集合方式批量新增)
本文主要介紹了MyBatis批量插入的五種方式小結(jié)(MyBatis以集合方式批量新增),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
SpringBoot如何導(dǎo)出Jar包并測(cè)試(使用IDEA)
這篇文章主要介紹了SpringBoot如何導(dǎo)出Jar包并測(cè)試(使用IDEA),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
最簡(jiǎn)單的MyBatis Plus的多表聯(lián)接、分頁(yè)查詢實(shí)現(xiàn)方法
這篇文章主要介紹了最簡(jiǎn)單的MyBatis Plus的多表聯(lián)接、分頁(yè)查詢實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

