当Tomcat关闭时,在Spring Boot中关闭Executor服务

问题描述 投票:2回答:2

我在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,以便它有机会完成队列中的内容?谢谢!

java spring spring-boot executorservice shutdown
2个回答
1
投票

使用@PreDestroy注释进行注释。然后从那里执行executo服务的关闭。

@Configuration
class ExecutorServiceConfiguration {

    @Value("${"executor.thread.count"}")
    private int executorThreadCount;


     public static class MyExecutorService {
           private ThreadPoolExecutor executor;

           public MyExecutorService(ThreadPoolExecutor executor) {
               this.executor = executor;
           }
           @PreDestroy()
           public destroy() {
                  // destroy executor
           }
     }

    @Bean("executorThreadPool")
    public ThreadPoolExecutor cachedThreadPool() {
        return new ThreadPoolExecutor(executorThreadCount, executorThreadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    }

    @Bean
    public MyExecutorService configureDestroyableBean(ThreadPoolExecutor cachedThreadPool) 
    {
      return new MyExecutorService(cachedThreadPool);
    }

}

2
投票

您可以通过配置TomcatEmbeddedServletContainerFactory bean来挂钩Tomcat生命周期。它有一个方法addContextLifecycleListeners,它允许你实例化你自己的LifecycleListener并处理你想要的任何Tomcat Lifecycle Events(例如,通过在你的awaitTermination上调用ExecutorService)。

@Configuration
public class TomcatConfiguration implements LifecycleListener {

    @Autowire("executorThreadPool")
    private ThreadPoolExecutor executor;

    @Bean
    public EmbeddedServletContainerFactory embeddedTomcatFactory() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.addContextLifecycleListeners(this);
        return factory;
    }

    @Override
    public void lifecycleEvent(LifeCycleEvent event) {
        //if check for correct event        
        executor.awaitTermination();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.