別再用 kill -9 了,這才是微服務(wù)上下線的正確姿勢(shì)!

- 前言 -

- 優(yōu)雅下線 -
基礎(chǔ)下線(Spring/SpringBoot/內(nèi)置容器)
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
close();
}
});
程序正常退出; 使用System.exit(); 終端使用Ctrl+C; 使用Kill pid干掉進(jìn)程。
public void registerShutdownHook() {
if (this.shutdownHook == null) {
this.shutdownHook = new Thread() {
public void run() {
synchronized(AbstractApplicationContext.this.startupShutdownMonitor) {
AbstractApplicationContext.this.doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
public void destroy() {
this.close();
}
public void close() {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.doClose();
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
} catch (IllegalStateException var4) {
;
}
}
}
}
protected void doClose() {
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
this.publishEvent((ApplicationEvent)(new ContextClosedEvent(this)));
} catch (Throwable var3) {
this.logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", var3);
}
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
} catch (Throwable var2) {
this.logger.warn("Exception thrown from LifecycleProcessor on context close", var2);
}
}
this.destroyBeans();
this.closeBeanFactory();
this.onClose();
this.active.set(false);
}
}
@Component
public class GracefulShutdownListener implements ApplicationListener<ContextClosedEvent> {
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent){
//注銷邏輯
zookeeperRegistry.unregister(mCurrentServiceURL);
...
}
}
可能會(huì)有疑問的是,微服務(wù)中一般來說,注銷服務(wù)往往是優(yōu)雅下線的第一步,接著才會(huì)執(zhí)行停機(jī)操作,那么這個(gè)時(shí)候流量進(jìn)來怎么辦呢?

- Docker 中的下線 -

- 外置容器的 shutdown 腳本(Jetty) -


- 優(yōu)雅上線 -
springboot 內(nèi)置容器優(yōu)雅上線
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
healthCheckerProcessor.init();
healthIndicatorProcessor.init();
afterHealthCheckCallbackProcessor.init();
publishBeforeHealthCheckEvent();
readinessHealthCheck();
}
@Component
public class GracefulStartupListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent){
//注冊(cè)邏輯 優(yōu)雅上線
apiRegister.register(urls);
...
}
}
外置容器(Jetty)優(yōu)雅上線

作者:fredalxin
來源:
https://fredal.xin/graceful-soa-updown

評(píng)論
圖片
表情
