Dubbo应用优雅停机实践

网上相关的帖子很多,主要方法也都是加钩子HOOK,这里我对优雅停机进行了实践

目前不管是dubboX、apache的dubbo、alibaba的dubbo都没有实现真正意义上的优雅停机(截止20191231)

标红是重点,目前jar中自带的hook并不能满足先从注册中心移除、再销毁容器的顺序,且激活hook需要在JVM变量(启动参数)中配置dubbo.shutdown.hook=true参数

这里我通过监听事件,在spring容器初始化后,自己注册了一个HOOK,new TpspShutDownHook()

@Slf4j
public class ShutDownListener implements ApplicationListener {


    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof ContextRefreshedEvent) {
          if(((ContextRefreshedEvent) event).getApplicationContext().getParent() != null ){
            return;
          }
        //root application context 没有parent,他就是老大.
        log.info("##############################");
        log.info("##############################");
        log.info("#### spring is refreshed #####");
        Runtime.getRuntime().addShutdownHook(new TpspShutDownHook());
        log.info("##############################");
        }else  if(event instanceof ContextClosedEvent) {
            //root application context 没有parent,他就是老大.
            log.info("##Context is going to closed##");
            log.info("##############################");
            log.info("##############################");
        }
    }
}

TpspShutDownHook.class


@Slf4j
public class TpspShutDownHook extends  Thread {

    @Override
    public void run() {

        try {
            log.info("##############################");
            log.info("#dubbo is going to destroyed#");
            //先从ZK注册中心,消除dubbo,防止流量再进来
            TpspProtocolConfig.destroyAll();
        } catch (Exception e) {
            log.error("优雅关机异常", e);
        }

    }

}

具体的就是改造了ProtocolConfig的代码,先从注册中心移除提供者,然后再销毁各端口协议

    public static void destroyAll() {
        AbstractRegistryFactory.destroyAll();
        log.info("#dubbo is destroying............#");
        try {
            //等待8秒,等ZK中心清除干净
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            log.error("dubbo优雅关机异常", e);
        }
        ExtensionLoader loader = ExtensionLoader.getExtensionLoader(Protocol.class);
        for (String protocolName : loader.getLoadedExtensions()) {
            try {
                Protocol protocol = loader.getLoadedExtension(protocolName);
                if (protocol != null) {
                    protocol.destroy();
                }
            } catch (Throwable t) {
                logger.warn(t.getMessage(), t);
            }
        }
        log.info("#dubbo is destroyed#");
    }

 

 

 

你可能感兴趣的:(开发笔记-杂)