求求你们别再用 kill -9 了,这才是 Spring Boot 停机的正确方式!!!

面试官:Spring Boot 停止服务的方法有哪些? 第三种方法,在springboot启动的时候将进程号写入一个app.pid文件,生成的路径是可以指定的,可以通过命令 cat /Users/huangqingshi/app.id | xargs kill 命令直接停止服务,这个时候bean对象的PreDestroy方法也会调用的。在使用Springboot的时候,都要涉及到服务的停止和启动,当我们停止服务的时候,很多时候大家都是kill -9 直接把程序进程杀掉,这样程序不会执行优雅的关闭。这样程序在关闭的时候也会调用PreDestroy注解。 阅读详情
来源:blog.youkuaiyun.com/alex_xfboy/
article/details/90404691




由于业务系统中大量使用了spring Boot embedded tomcat的模式运行,在一些运维脚本中经常看到Linux 中kill指令,然而它的使用也有些讲究,要思考如何能做到优雅停机。

何为优雅关机

就是为确保应用关闭时,通知应用进程释放所占用的资源

  • 线程池,shutdown(不接受新任务等待处理完)还是shutdownNow(调用Thread.interrupt进行中断)

  • socket 链接,比如:netty、mq

  • 告知注册中心快速下线(靠心跳机制客服早都跳起来了),比如:eureka

  • 清理临时文件,比如:poi

  • 各种堆内堆外内存释放

总之,进程强行终止会带来数据丢失或者终端无法恢复到正常状态,在分布式环境下还可能导致数据不一致的情况。

kill指令

kill -9 pid可以模拟了一次系统宕机,系统断电等极端情况,而kill -15 pid则是等待应用关闭,执行阻塞操作,有时候也会出现无法关闭应用的情况(线上理想情况下,是bug就该寻根溯源)

#查看jvm进程pid
jps
#列出所有信号名称
kill -l
 
# Windows下信号常量值
# 简称  全称    数值 
# INT   SIGINT     2       Ctrl+C中断
# ILL   SIGILL     4       非法指令
# FPE   SIGFPE     8       floating point exception(浮点异常)
# SEGV  SIGSEGV    11      segment violation(段错误)
# TERM  SIGTERM    5       Software termination signal from kill(Kill发出的软件终止)
# BREAK SIGBREAK   21      Ctrl-Break sequence(Ctrl+Break中断)
# ABRT  SIGABRT    22      abnormal termination triggered by abort call(Abort)
 
#linux信号常量值
# 简称  全称  数值  
# HUP   SIGHUP      1    终端断线  
# INT   SIGINT      2    中断(同 Ctrl + C)        
# QUIT  SIGQUIT     3    退出(同 Ctrl + \)         
# KILL  SIGKILL     9    强制终止         
# TERM  SIGTERM     15    终止         
# CONT  SIGCONT     18    继续(与STOP相反, fg/bg命令)         
# STOP  SIGSTOP     19    暂停(同 Ctrl + Z)        
#....
 
#可以理解为操作系统从内核级别强行杀死某个进程
kill -9 pid 
#理解为发送一个通知,等待应用主动关闭
kill -15 pid
#也支持信号常量值全称或简写(就是去掉SIG后)
kill -l KILL

思考:jvm是如何接受处理linux信号量的?

当然是在jvm启动时就加载了自定义SignalHandler,关闭jvm时触发对应的handle。

public interface SignalHandler {
    SignalHandler SIG_DFL = new NativeSignalHandler(0L);
    SignalHandler SIG_IGN = new NativeSignalHandler(1L);
 
    void handle(Signal var1);
}
class Terminator {
    private static SignalHandler handler = null;
 
    Terminator() {
    }
    //jvm设置SignalHandler,在System.initializeSystemClass中触发
    static void setup() {
        if (handler == null) {
            SignalHandler var0 = new SignalHandler() {
                public void handle(Signal var1) {
                    Shutdown.exit(var1.getNumber() + 128);//调用Shutdown.exit
                }
            };
            handler = var0;
 
            try {
                Signal.handle(new Signal("INT"), var0);//中断时
            } catch (IllegalArgumentException var3) {
                ;
            }
 
            try {
                Signal.handle(new Signal("TERM"), var0);//终止时
            } catch (IllegalArgumentException var2) {
                ;
            }
 
        }
    }
}

Runtime.addShutdownHook

在了解Shutdown.exit之前,先看Runtime.getRuntime().addShutdownHook(shutdownHook);则是为jvm中增加一个关闭的钩子,当jvm关闭的时候调用。

public class Runtime {
    public void addShutdownHook(Thread hook) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("shutdownHooks"));
        }
        ApplicationShutdownHooks.add(hook);
    }
}
class ApplicationShutdownHooks {
    /* The set of registered hooks */
    private static IdentityHashMap<Thread, Thread> hooks;
    static synchronized void add(Thread hook) {
        if(hooks == null)
            throw new IllegalStateException("Shutdown in progress");
 
        if (hook.isAlive())
            throw new IllegalArgumentException("Hook already running");
 
        if (hooks.containsKey(hook))
            throw new IllegalArgumentException("Hook previously registered");
 
        hooks.put(hook, hook);
    }
}
//它含数据结构和逻辑管理虚拟机关闭序列
class Shutdown {
    /* Shutdown 系列状态*/
    private static final int RUNNING = 0;
    private static final int HOOKS = 1;
    private static final int FINALIZERS = 2;
    private static int state = RUNNING;
    /* 是否应该运行所以finalizers来exit? */
    private static boolean runFinalizersOnExit = false;
    // 系统关闭钩子注册一个预定义的插槽.
    // 关闭钩子的列表如下:
    // (0) Console restore hook
    // (1) Application hooks
    // (2) DeleteOnExit hook
    private static final int MAX_SYSTEM_HOOKS = 10;
    private static final Runnable[] hooks = new Runnable[MAX_SYSTEM_HOOKS];
    // 当前运行关闭钩子的钩子的索引
    private static int currentRunningHook = 0;
    /* 前面的静态字段由这个锁保护 */
    private static class Lock { };
    private static Object lock = new Lock();
 
    /* 为native halt方法提供锁对象 */
    private static Object haltLock = new Lock();
 
    static void add(int slot, boolean registerShutdownInProgress, Runnable hook) {
        synchronized (lock) {
            if (hooks[slot] != null)
                throw new InternalError("Shutdown hook at slot " + slot + " already registered");
 
            if (!registerShutdownInProgress) {//执行shutdown过程中不添加hook
                if (state > RUNNING)//如果已经在执行shutdown操作不能添加hook
                    throw new IllegalStateException("Shutdown in progress");
            } else {//如果hooks已经执行完毕不能再添加hook。如果正在执行hooks时,添加的槽点小于当前执行的槽点位置也不能添加
                if (state > HOOKS || (state == HOOKS && slot <= currentRunningHook))
                    throw new IllegalStateException("Shutdown in progress");
            }
 
            hooks[slot] = hook;
        }
    }
    /* 执行所有注册的hooks
     */
    private static void runHooks() {
        for (int i=0; i < MAX_SYSTEM_HOOKS; i++) {
            try {
                Runnable hook;
                synchronized (lock) {
                    // acquire the lock to make sure the hook registered during
                    // shutdown is visible here.
                    currentRunningHook = i;
                    hook = hooks[i];
                }
                if (hook != null) hook.run();
            } catch(Throwable t) {
                if (t instanceof ThreadDeath) {
                    ThreadDeath td = (ThreadDeath)t;
                    throw td;
                }
            }
        }
    }
    /* 关闭JVM的操作
     */
    static void halt(int status) {
        synchronized (haltLock) {
            halt0(status);
        }
    }
    //JNI方法
    static native void halt0(int status);
    // shutdown的执行顺序:runHooks > runFinalizersOnExit
    private static void sequence() {
        synchronized (lock) {
            /* Guard against the possibility of a daemon thread invoking exit
             * after DestroyJavaVM initiates the shutdown sequence
             */
            if (state != HOOKS) return;
        }
        runHooks();
        boolean rfoe;
        synchronized (lock) {
            state = FINALIZERS;
            rfoe = runFinalizersOnExit;
        }
        if (rfoe) runAllFinalizers();
    }
    //Runtime.exit时执行,runHooks > runFinalizersOnExit > halt
    static void exit(int status) {
        boolean runMoreFinalizers = false;
        synchronized (lock) {
            if (status != 0) runFinalizersOnExit = false;
            switch (state) {
            case RUNNING:       /* Initiate shutdown */
                state = HOOKS;
                break;
            case HOOKS:         /* Stall and halt */
                break;
            case FINALIZERS:
                if (status != 0) {
                    /* Halt immediately on nonzero status */
                    halt(status);
                } else {
                    /* Compatibility with old behavior:
                     * Run more finalizers and then halt
                     */
                    runMoreFinalizers = runFinalizersOnExit;
                }
                break;
            }
        }
        if (runMoreFinalizers) {
            runAllFinalizers();
            halt(status);
        }
        synchronized (Shutdown.class) {
            /* Synchronize on the class object, causing any other thread
             * that attempts to initiate shutdown to stall indefinitely
             */
            sequence();
            halt(status);
        }
    }
    //shutdown操作,与exit不同的是不做halt操作(关闭JVM)
    static void shutdown() {
        synchronized (lock) {
            switch (state) {
            case RUNNING:       /* Initiate shutdown */
                state = HOOKS;
                break;
            case HOOKS:         /* Stall and then return */
            case FINALIZERS:
                break;
            }
        }
        synchronized (Shutdown.class) {
            sequence();
        }
    }
}

spring 3.2.12

在spring中通过ContextClosedEvent事件来触发一些动作(可以拓展),主要通过LifecycleProcessor.onClose来做stopBeans。由此可见spring也基于jvm做了拓展。

public abstract class AbstractApplicationContext extends DefaultResourceLoader {
 public void registerShutdownHook() {
  if (this.shutdownHook == null) {
   // No shutdown hook registered yet.
   this.shutdownHook = new Thread() {
    @Override
    public void run() {
     doClose();
    }
   };
   Runtime.getRuntime().addShutdownHook(this.shutdownHook);
  }
 }
 protected void doClose() {
  boolean actuallyClose;
  synchronized (this.activeMonitor) {
   actuallyClose = this.active && !this.closed;
   this.closed = true;
  }
 
  if (actuallyClose) {
   if (logger.isInfoEnabled()) {
    logger.info("Closing " + this);
   }
 
   LiveBeansView.unregisterApplicationContext(this);
 
   try {
    //发布应用内的关闭事件
    publishEvent(new ContextClosedEvent(this));
   }
   catch (Throwable ex) {
    logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
   }
 
   // 停止所有的Lifecycle beans.
   try {
    getLifecycleProcessor().onClose();
   }
   catch (Throwable ex) {
    logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
   }
 
   // 销毁spring 的 BeanFactory可能会缓存单例的 Bean.
   destroyBeans();
 
   // 关闭当前应用上下文(BeanFactory)
   closeBeanFactory();
 
   // 执行子类的关闭逻辑
   onClose();
 
   synchronized (this.activeMonitor) {
    this.active = false;
   }
  }
 } 
}
public interface LifecycleProcessor extends Lifecycle {
 /**
  * Notification of context refresh, e.g. for auto-starting components.
  */
 void onRefresh();
 
 /**
  * Notification of context close phase, e.g. for auto-stopping components.
  */
 void onClose();
}

spring boot

到这里就进入重点了,spring boot中有spring-boot-starter-actuator模块提供了一个 restful 接口,用于优雅停机。

执行请求curl -X POST http://127.0.0.1:8088/shutdown,待关闭成功则返回提示。

注:线上环境该url需要设置权限,可配合 spring-security使用或在nginx中限制内网访问

#启用shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false
#可统一指定所有endpoints的路径
management.context-path=/manage
#指定管理端口和IP
management.port=8088
management.address=127.0.0.1

#开启shutdown的安全验证(spring-security)
endpoints.shutdown.sensitive=true
#验证用户名
security.user.name=admin
#验证密码
security.user.password=secret
#角色
management.security.role=SUPERUSER

spring boot的shutdown原理也不复杂,其实还是通过调用AbstractApplicationContext.close实现的。

@ConfigurationProperties(
    prefix = "endpoints.shutdown"
)
public class ShutdownMvcEndpoint extends EndpointMvcAdapter {
    public ShutdownMvcEndpoint(ShutdownEndpoint delegate) {
        super(delegate);
    }
    //post请求
    @PostMapping(
        produces = {"application/vnd.spring-boot.actuator.v1+json", "application/json"}
    )
    @ResponseBody
    public Object invoke() {
        return !this.getDelegate().isEnabled() ? new ResponseEntity(Collections.singletonMap("message", "This endpoint is disabled"), HttpStatus.NOT_FOUND) : super.invoke();
    }
}
@ConfigurationProperties(
    prefix = "endpoints.shutdown"
)
public class ShutdownEndpoint extends AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {
    private static final Map<String, Object> NO_CONTEXT_MESSAGE = Collections.unmodifiableMap(Collections.singletonMap("message", "No context to shutdown."));
    private static final Map<String, Object> SHUTDOWN_MESSAGE = Collections.unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye..."));
    private ConfigurableApplicationContext context;
 
    public ShutdownEndpoint() {
        super("shutdown", true, false);
    }
    //执行关闭
    public Map<String, Object> invoke() {
        if (this.context == null) {
            return NO_CONTEXT_MESSAGE;
        } else {
            boolean var6 = false;
 
            Map var1;
 
            class NamelessClass_1 implements Runnable {
                NamelessClass_1() {
                }
 
                public void run() {
                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException var2) {
                        Thread.currentThread().interrupt();
                    }
                    //这个调用的就是AbstractApplicationContext.close
                    ShutdownEndpoint.this.context.close();
                }
            }
 
            try {
                var6 = true;
                var1 = SHUTDOWN_MESSAGE;
                var6 = false;
            } finally {
                if (var6) {
                    Thread thread = new Thread(new NamelessClass_1());
                    thread.setContextClassLoader(this.getClass().getClassLoader());
                    thread.start();
                }
            }
 
            Thread thread = new Thread(new NamelessClass_1());
            thread.setContextClassLoader(this.getClass().getClassLoader());
            thread.start();
            return var1;
        }
    }
}
全面分析总结解决Could not transfer artifact org.apache.maven.plugins等此类问题的方法 全面分析总结解决Could not transfer artifact org.apache.maven.plugins,Could not transfer artifact xxx from/to xxx等此类问题的方法 阅读详情

相关推荐

mobaXterm连接vmWare虚拟机上的centOS7提示连接失败的解决方法

1.问题描述: mobaXterm安装后连接虚拟机vmWare上的centOS7发现连接不上,如下图所示: 2.解决方法 先是查了一下centOS的ip 开始错误的以为 virbr0: 后面的inet就是虚拟机的IP 实则不然(正确的ip是在ens33后面的inet中的ip,大佬们勿喷) 这个值需要配置一下的,具体配置过程如下: step1: 进入centOS下的/...

hss19214的博客 7892

Springboot优雅停机-Springboot的shutdown实现

Springboot优雅停机

一瓶绿茶三元钱 9406

开关电源三大基本拓扑:反激、正激与桥式选型本质

开关电源拓扑是电力电子系统设计的核心基础概念,其本质决定能量传递路径、器件应力分布与系统物理边界。反激拓扑以耦合电感形式实现隔离与升降压,适用于小功率AC-DC场景;正激拓扑依赖实时能量传递与强制复位机制,支撑中功率高效率需求;桥式拓扑(含推挽/半桥/全桥)通过电压应力分摊与双向磁化,成为大功率系统的刚性选择。理解三者在磁芯工作模式、电流连续性、直流偏磁抑制等方面的原理差异,直接关系到效率、温升、EMI及可靠性等关键技术指标。本文聚焦反激、正激、桥式三大工程级基本拓扑的物理本质与落地约束,揭示从需求参数到电

cqwmy840702的博客 381

SpringBoot 优雅停止服务的几种方法

编写一个sh脚本,通过grep查找到我们项目的pid,然后先使用kill-15pid,然后sleep一下,然后在超找pid,如果没找到,说明已经关闭了,如果找到了,说明关闭失败了,那么就使用kill-9pid强制关闭进程了。SpringBoot提供的actuator的功能,它可以执行shutdown,health,info等,默认情况下,actuator的shutdown是disable的,我们需要打开它。利用actuator也是停止服务的方式,在下面会使用到,这里先把依赖添加进来。......

Park33的博客 5871

飞常准小程序接口逆向分析:如何破解航班查询的签名机制

本文深度解析了飞常准小程序航班查询接口的安全机制,重点剖析了其基于MD5和参数排序的签名算法。通过逆向分析核心代码,详细阐述了签名生成流程,并提供了Python实现的签名生成器与调试技巧,为开发者理解与模拟此类接口调用提供了实战指南。

zz67890的博客 536

【嵌入式Linux】EC20模块多运营商自适应PPP拨号实战:从IMSI识别到网络配置

本文详细介绍了在嵌入式Linux系统中,如何基于EC20 4G模块实现多运营商自适应PPP拨号。通过解析SIM卡的IMSI识别运营商,并动态配置对应的APN和拨号参数,结合AT指令交互与健壮的pppd脚本,解决了设备跨地域部署时的网络自动连接问题,提升了物联网设备的部署效率和稳定性。

fox11的博客 905

SpringBoot下实现Shutdown Hook的几种方式

在应用中,经常希望在JVM关闭时做一些清理的动作,本文陈述几种常用的实现方式。 1、JVM自带的shutdownHook Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("shutdown hook, jvm demo"))); 特点: jvm自带,使用方便,多个钩子间是并行执行的。 2、监听Spring的ContextClosedEvent 关于ContextClosedEvent等事件描述,可以参照以下示例(内容来自S

yi_chao_jiang的专栏 7387

ADS基础教程22 - 有限元电磁仿真(FEM)

一、引言二、FEM操作过程1.新建Layout1.新建Layout2.EM设置3.设置Frequency plan4.设置Output plan5.设置Options6.设置网格频率7.仿真结果三、总结介绍了在ADS中如何进行FEM仿真过程。END!}}END!

XZ_ZC的博客 2584

Spring Boot 的优雅启停:确保停机不影响交易

多中心并行发版:各中心并行升级,确保始终有可用实例。服务下线前的流量切换:使用服务注册中心(如 Eureka)将待下线实例置为“DOWN”。进程关闭信号选择:使用 kill -15(SIGTERM)触发优雅关闭,而非kill -9(SIGKILL)。线程池的优雅停止:配置线程池等待任务完成,避免强制中断。Spring Boot 2.3 内置优雅关机:启用,设置超时时间。启动时的优雅准备:检测依赖、初始化资源,确保服务就绪后再接受流量。优雅启停是系统稳定运行的关键。

sc35262的博客 1170

豆包手机为什么能自己“玩手机”?原理是什么?豆包手机系统运行机制深度解析:读屏、抓取、推理链路全拆解

作为一个每天被前端 Bug 打醒的程序员,我这一阵子在关注“豆包手机”这个关键词,刷到的相关视频简直铺天盖地。朋友们,说句实话,我一开始也只是抱着“看看热闹”的心态,最近一位博主下面的内容,不是“它能做什么”,而是。如果你之前看过很多评测,这篇文章会给你完全不一样的视角。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1018

基于 STM32 设计的 HC05 蓝牙音箱

本项目介绍如何使用 STM32 微控制器和 HC05 蓝牙模块设计一个简单的蓝牙音箱。该音箱可以接收来自手机或其他蓝牙设备的音频数据,并通过扬声器播放。该项目展示了如何使用 STM32 微控制器和 HC05 蓝牙模块设计一个简单的蓝牙音箱。易于实现功能实用可扩展性强如果您需要开发一个蓝牙音箱,该项目可以作为参考。

走向CTO的路上... 2473
上一篇: 五个维度,解析 Spring 中 @Autowired 和 @Resource 的区别
下一篇: MySQL 巨坑:永远不要在 MySQL 中使用 UTF-8!!
Java思维导图
博客等级 码龄10年 306粉丝 71原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值