mem*_*und 5 java spring spring-mvc resttemplate
我正在使用springwithRestTemplate向POST网络服务器发送请求。
当我的应用程序关闭时(例如从 tomcat 中取消部署),关闭应该被延迟,直到收到所有挂起的响应(在超时内)。
restTemplateHttpComponentsClientHttpRequestFactory在幕后使用。
问题:我怎么知道spring延迟关机?@PreDestroy可能是一种可能性,但是如何检测 restTemplate 上的待处理请求?
我认为没有现成的解决方案,如https://github.com/spring-projects/spring-boot/issues/4657中所述
对于 Tomcat,下面的代码应该可以工作
@Component
@Scope("singleton")
public class ApplicationContextClosedListener implements ApplicationListener<ContextClosedEvent>, TomcatConnectorCustomizer {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextClosedListener.class);
private volatile Connector connector;
@Value("${timeout}")
private Integer timeout;
@Override
public void customize(Connector connector) {
this.connector = connector;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
if (connector != null) {
shutdownGracefully();
}
}
private void shutdownGracefully() {
connector.pause();
Executor executor = connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
try {
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(timeout, TimeUnit.SECONDS)) {
LOGGER.warn("Shutdown: Tomcat thread pool did not shut down gracefully within specified period. Proceeding with forceful shutdown");
}
threadPoolExecutor.shutdownNow();
LOGGER.info("Shutdown: the executor shutdown completed");
} catch (InterruptedException ex) {
LOGGER.error("Shutdown: Interrupt signal received");
threadPoolExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1659 次 |
| 最近记录: |