服务器崩溃/关闭后恢复异步线程池任务执行器

Luc*_*.de 5 java spring asynchronous executor

我有一个 Spring rest 控制器,它使用 Spring 的 @Async 方法调用异步方法,并立即向客户端返回一个 http 202 代码(已接受)。(异步作业很繁重,可能导致超时)。所以实际上,在异步任务结束时,我会向客户发送一封电子邮件,告诉他请求的状态。

一切正常,但我问自己,如果我的服务器/jvm 崩溃或关闭,我该怎么办?我的客户会收到一个 202 代码,并且永远不会收到状态电子邮件。

有没有一种方法可以(实时)同步数据库甚至文件中的 ThreadPoolTask​​Executor,让服务器在启动时恢复,而无需我自己管理复杂的规则和演变状态?

这是我的 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 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());
}
Run Code Online (Sandbox Code Playgroud)

}

谢谢

swi*_*ler 0

对于 Web 服务器关闭,Java Web 应用程序中的应用程序生命周期将通知ServletContextListener。如果您提供 ServletContextListener 的实现,您可以将“已处理内容”逻辑放入该contextDestroyed方法中。

当 Web 服务器或应用程序再次启动时,侦听器可用于恢复并重新处理使用该contextInitialized方法的作业的未处理项目。

另一种选择是使用Spring 销毁回调并将逻辑放在这里。

华泰