我有一個Spring Rest控制器,它使用Spring的@Async方法調用異步方法,並立即返回一個http 202代碼(Accepted)給客戶端(異步作業很重並可能導致超時)。 實際上,在異步任務結束時,我向客戶發送一封電子郵件,告訴他他的請求狀態。服務器崩潰/關閉後恢復Asynch ThreadPoolTaskexecutor
一切正常,但我問自己,如果我的服務器/ jvm崩潰或關閉,我該怎麼辦?我的客戶將收到202代碼,並且永遠不會收到狀態電子郵件。
是否有一種方法可以實時同步(實時)數據庫中的ThreadPoolTaskExecutor,或者甚至在文件中讓服務器在啓動時恢復,而無需通過複雜的規則和進化狀態來自行管理?
這裏是我的遺囑執行人配置
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("asyncTaskExecutor-");
executor.setAwaitTerminationSeconds(120);
executor.setKeepAliveSeconds(30);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
是啓動異步任務
@RequestMapping(value = "/testAsync", method = RequestMethod.GET)
public void testAsync() throws InterruptedException{
businessService.doHeavyThings();
}
調用的異步方法控制器:
@Async
public void doHeavyThings() throws InterruptedException {
LOGGER.error("Start doHeavyThings with configured executor - " + Thread.currentThread().getName() + " at " + new Date());
Thread.sleep(5000L);
LOGGER.error("Stop doHeavyThings with configured executor - " + Thread.currentThread().getName() + " at " + new Date());
}
}
THX