我有一个 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();
}
}
Run Code Online (Sandbox Code Playgroud)
启动异步任务的控制器
@RequestMapping(value = "/testAsync", method = RequestMethod.GET)
public void testAsync() throws InterruptedException{
businessService.doHeavyThings();
}
Run Code Online (Sandbox Code Playgroud)
异步方法调用:
@Async
public void doHeavyThings() throws …Run Code Online (Sandbox Code Playgroud)