优雅关闭springboot应用

1.添加钩子函数,钩子函数中指定要调用的方法

@PostConstruct
    public void run() {
        this.zkClient.start(this);
        this.schedulerService.start();
        try {
            logger.info("start Quartz server...");
            QuartzExecutors.getInstance().start();
        } catch (Exception e) {
            try {
                QuartzExecutors.getInstance().shutdown();
            } catch (SchedulerException e1) {
                logger.error("QuartzExecutors shutdown failed : " + e1.getMessage(), e1);
            }
            logger.error("start Quartz failed", e);
        }
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (Stopper.isRunning()) {
                    close("shutdownHook");
                }
            }
        }));
    }

2.指定close方法要执行的一些动作

public void close(String cause) {

        try {
            //execute only once
            if (Stopper.isStopped()) {
                return;
            }

            logger.info("master server is stopping ..., cause : {}", cause);

            // set stop signal is true
            Stopper.stop();

            try {
                //thread sleep 3 seconds for thread quietly stop
                Thread.sleep(3000L);
            } catch (Exception e) {
                logger.warn("thread sleep exception ", e);
            }
            //close
            this.schedulerService.close();
            this.zkClient.close();
            //close quartz
            try {
                QuartzExecutors.getInstance().shutdown();
                logger.info("Quartz service stopped");
            } catch (Exception e) {
                logger.warn("Quartz service stopped exception:{}", e.getMessage());
            }
        } catch (Exception e) {
            logger.error("master server stop exception ", e);
        } finally {
//            System.exit(-1);
        }
    }

3.使用kill命令验证

kill pid
原文地址:https://www.cnblogs.com/PythonOrg/p/14581475.html