Tomcat关闭时Spring Boot中Executor服务的关闭

我在 Spring Boot 中配置了一个执行器服务,如下所示:


@Configuration

@PropertySource({ "classpath:executor.properties" })

public class ExecutorServiceConfig {


    @Value("${"executor.thread.count"}")

    private int executorThreadCount;


    @Bean("executorThreadPool")

    public ThreadPoolExecutor cachedThreadPool() {

        return new ThreadPoolExecutor(executorThreadCount, executorThreadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

    }

}

该应用程序部署在一个独立的 Tomcat 实例上。当Tomcat服务器关闭时,我发现队列中还有未完成的任务。结果,我会丢失数据。有没有办法让我在这个执行程序服务上调用 awaitTermination 以便它有机会完成队列中的内容?谢谢!


30秒到达战场
浏览 223回答 2
2回答

森林海

使用注释进行@PreDestroy注释。然后从那里执行执行服务的关闭。@Configurationclass ExecutorServiceConfiguration {&nbsp; &nbsp; @Value("${"executor.thread.count"}")&nbsp; &nbsp; private int executorThreadCount;&nbsp; &nbsp; &nbsp;public static class MyExecutorService {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;private ThreadPoolExecutor executor;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public MyExecutorService(ThreadPoolExecutor executor) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.executor = executor;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;@PreDestroy()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;public destroy() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // destroy executor&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; @Bean("executorThreadPool")&nbsp; &nbsp; public ThreadPoolExecutor cachedThreadPool() {&nbsp; &nbsp; &nbsp; &nbsp; return new ThreadPoolExecutor(executorThreadCount, executorThreadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());&nbsp; &nbsp; }&nbsp; &nbsp; @Bean&nbsp; &nbsp; public MyExecutorService configureDestroyableBean(ThreadPoolExecutor cachedThreadPool)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; return new MyExecutorService(cachedThreadPool);&nbsp; &nbsp; }}

有只小跳蛙

您可以通过配置TomcatEmbeddedServletContainerFactorybean 来挂钩到 Tomcat 生命周期。它有一个方法 addContextLifecycleListeners 允许您实例化您自己的 LifecycleListener 并根据需要处理任何Tomcat 生命周期事件(例如,通过调用awaitTermination您的ExecutorService)。@Configurationpublic class TomcatConfiguration implements LifecycleListener {&nbsp; &nbsp; @Autowire("executorThreadPool")&nbsp; &nbsp; private ThreadPoolExecutor executor;&nbsp; &nbsp; @Bean&nbsp; &nbsp; public EmbeddedServletContainerFactory embeddedTomcatFactory() {&nbsp; &nbsp; &nbsp; &nbsp; TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();&nbsp; &nbsp; &nbsp; &nbsp; factory.addContextLifecycleListeners(this);&nbsp; &nbsp; &nbsp; &nbsp; return factory;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void lifecycleEvent(LifeCycleEvent event) {&nbsp; &nbsp; &nbsp; &nbsp; //if check for correct event&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; executor.awaitTermination();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java