我有一个
Spring rest控制器,它使用Spring的@Async方法调用异步方法,并立即向客户端返回一个http 202代码(Accepted).(异步作业很重,可能导致超时).
实际上,在异步任务结束时,我正在向客户发送一封电子邮件,告诉他他的请求的状态.
一切正常,但我问自己,如果我的服务器/ jvm崩溃或者它关闭了我该怎么办?我的客户将收到202代码,永远不会收到状态电子邮件.
有没有办法在数据库中甚至在文件中同步(实时)ThreadPoolTaskExecutor,让服务器在启动时恢复而不用自己管理复杂规则和进化状态?
这是我的Executor配置
@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());
}
}
谢谢