2 回答
TA贡献2011条经验 获得超2个赞
使用注释进行@PreDestroy注释。然后从那里执行执行服务的关闭。
@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);
}
}
TA贡献1824条经验 获得超8个赞
您可以通过配置TomcatEmbeddedServletContainerFactorybean 来挂钩到 Tomcat 生命周期。它有一个方法 addContextLifecycleListeners 允许您实例化您自己的 LifecycleListener 并根据需要处理任何Tomcat 生命周期事件(例如,通过调用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();
}
}
添加回答
举报