【发布时间】:2016-12-09 14:16:57
【问题描述】:
我有一个 Spring REST 控制器,它使用 Spring 的 @Async 方法调用异步方法,并立即向客户端返回一个 http 202 代码(已接受)。(异步作业很繁重,可能导致超时)。 所以实际上,在异步任务结束时,我正在向客户发送一封电子邮件,告诉他他的请求状态。
一切正常,但我问自己,如果我的服务器/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());
}
}
谢谢
【问题讨论】:
标签: java spring asynchronous executor