Spring異步線程池的接口類,其實質是java.util.concurrent.Executorjava
Spring 已經實現的異常線程池:bash
SimpleAsyncTaskExecutor
:不是真的線程池,這個類不重用線程,每次調用都會建立一個新的線程。 SyncTaskExecutor
:這個類沒有實現異步調用,只是一個同步操做。只適用於不須要多線程的地方 ConcurrentTaskExecutor
:Executor的適配類,不推薦使用。若是ThreadPoolTaskExecutor不知足要求時,才用考慮使用這個類 SimpleThreadPoolTaskExecutor
:是Quartz的SimpleThreadPool的類。線程池同時被quartz和非quartz使用,才須要使用此類 ThreadPoolTaskExecutor
:最常使用,推薦。 其實質是對java.util.concurrent.ThreadPoolExecutor的包裝 @Async
,就會啓動一個新的線程去執行。
SpringBoot中開啓異步支持很是簡單,只須要在配置類上面加上註解 @EnableAsync
,同時定義本身的線程池便可。 也能夠不定義本身的線程池,則使用系統默認的線程池。這個註解能夠放在Application啓動類上,可是更推薦放在配置類上面。 咱們能夠實現 AsyncConfigurerc
接口,也能夠繼承 AsyncConfigurerSupport
類來實現。多線程
在方法getAsyncExecutor()中建立線程池的時候,必須使用 executor.initialize()
,否則在調用時會報線程池未初始化的異常。異步
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(100);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60 * 10);
executor.setThreadNamePrefix("AsyncThread-");
executor.initialize(); //若是不初始化,致使找到不到執行器
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncExceptionHandler();
}
}
複製代碼
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(AsyncExceptionHandler.class);
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
log.info("Async method has uncaught exception, params: " + params);
if (ex instanceof AsyncException) {
AsyncException asyncException = (AsyncException) ex;
log.info("asyncException:" + asyncException.getMsg());
}
log.error("Exception :", ex);
}
}
AsyncException:
public class AsyncException extends Exception {
private int code;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
複製代碼
在調用方法時,可能出現方法中拋出異常的狀況。Spring對於2種異步方法的異常處理機制以下:async
AsyncUncaughtExceptionHandler
處理異常
@Component
public class AsyncTask {
@Async
public void dealNoReturnTask(){
log.info("返回值爲void的異步調用開始" + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("返回值爲void的異步調用結束" + Thread.currentThread().getName());
}
@Async
public Future<String> dealHaveReturnTask(int i) {
log.info("asyncInvokeReturnFuture, parementer=" + i);
Future<String> future;
try {
Thread.sleep(1000 * i);
future = new AsyncResult<String>("success:" + i);
} catch (InterruptedException e) {
future = new AsyncResult<String>("error");
}
return future;
}
}
複製代碼
/**
* 測試異步任務
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
private static final Logger log = LoggerFactory.getLogger(ApplicationTests.class);
@Autowired
private AsyncTask asyncTask;
@Test
public void testAsync() throws InterruptedException, ExecutionException {
asyncTask.dealNoReturnTask();
Future<String> f = asyncTask.dealHaveReturnTask(5);
log.info("主線程執行finished");
log.info(f.get());
}
}
複製代碼
實際運行中,還出現過一個問題,一個Service中的方法調用本身的另外一個方法,而後我將這個方法加上@Async註解,然而並不起做用。 異步方法都應該放到單獨的異步任務Bean裏面去,而後將這個Bean注入到Service中便可ide