跳至主要內容

优雅的关闭项目

chanchaw大约 1 分钟javaspring

概述

linux 中使用 kill -9 [PID] 是强制关闭正在运行的项目,相当于拔掉电源,kill -15 [PID] 是通知应用程序自己关闭,所以后者是优雅关闭,而 windows 在命令行界面中 ctrl+c 是优雅关闭,所以通过 WinSW 制作为系统服务后就无法优雅关闭了。 spring2.3 以前的版本也是不支持优雅关闭的,在该版本及以上通过引用类库 spring-boot-starter-actuator 实现优雅关闭功能。

项目部署

spring2.3以上的 windows 端按照下面步骤制作

  1. 引入依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

配置文件做如下选项

#监控相关配置
management:
  endpoint:
    # 开启
    shutdown:
      enabled: true
  endpoints:
    web:
      # 只允许shutdown,为了安全,其它想要监控自行配置
      exposure:
        include: "shutdown"
      # 自定义请求路径,为了安全
      base-path: /xxx
  server:
    #自定义请求端口,为了安全
    port: 7080

同时做如下配置

# 开启优雅关闭
server:
  shutdown: graceful
# 配置强制结束时间,不配置的话默认30s
spring:
  lifecycle:
    timeout-per-shutdown-phase: 30s

之后通过发送 post 请求:url -X POST http://localhost:open in new window自定义端口/自定义路径/shutdown 关闭项目,如果是 spring2.3 以下版本则需要编程实现,这里不做介绍。