@
pvcxy18 public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(DemoApplication.class);
//启动, 关闭时延迟 30s 销毁容器
startWithDelayShutdown(springApplication,args, 30);
}
/**
* 延迟停机。服务关闭时,先主动下线服务,延迟一定时间后再关闭服务
* @
param springApplication
* @
param args
*/
public static void startWithDelayShutdown(SpringApplication springApplication, String[] args, Integer delaySeconds){
// 默认 deleay 30s
if(delaySeconds == null){
delaySeconds = 30;
}
//关闭自带的 SpringContextShutdownHook
springApplication.setRegisterShutdownHook(false);
//启动 Spring
ConfigurableApplicationContext context =
springApplication.run(args);
//注册自定义 SpringContextShutdownHook
Integer finalDelaySeconds = delaySeconds;
Thread shutdownHook = new Thread("MY-SpringContextShutdownHook") {
public void run() {
//我这里是 nacos ,其他注册中心都是一样的
log.info("服务停止,主动下线");
NacosAutoServiceRegistration nacosAutoServiceRegistration = SpringContextUtils.getBean(NacosAutoServiceRegistration.class);
nacosAutoServiceRegistration.stop();
//下线 30s 后停止
log.info("停止,休眠{}s", finalDelaySeconds);
try {
Thread.sleep(finalDelaySeconds *1000L);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
log.info("停止,休眠{}s 结束,销毁容器", finalDelaySeconds);
context.close();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}