【SpringBoot笔记】SpringBoot如何正确关闭应用

关闭Spring Boot应用程序,我们可以通过OS命令kill -9 进程ID 实现将进程杀死。但是,有没有一种更好的方式,比如通过REST请求实现?Spring Boot Actoator提供了实现。通过提供的shutdown服务可以实现安全的关闭Spring Boot应用。简单实用步骤如下:

step1:pom引入spring boot Actoator依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

step2:开启shutdown endpoint,默认是关闭的,需要在application.properties中开启shutdown endpoint

endpoints.shutdown.enabled=true   #启用shutdown
endpoints.shutdown.sensitive=false  #需要禁用密码验证,否则需要进行认证才能调用服务

step3:调用shutdown服务:

shutdown的默认urlhost:port/shutdown,当需要停止服务时,向服务器post该请求即可,如:
curl -X POST host:port/shutdown
将得到形如{"message":"Shutting down, bye..."}的响应

通过上面的设置即可实现关闭spring boot应用,但是你会发现,这样会十分不安全,只要通过服务调用即可关闭应用,所以,具体应用中常常需要进行安全认证,比如借助Spring boot security,步骤如下:

step1:pom.xml添加security依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

step2:开启安全验证,application.properties中变更配置:

endpoints.shutdown.sensitive=true #开启shutdown的安全验证

security.user.name=userName    #用户名

security.user.password=password             #密码

management.security.role=XX_ROLE#角色

step3:指定路径、IP、端口

endpoints.shutdown.path=/custompath     #指定shutdown的路径,如果需要统一指定应用的路径,则可以用management.context-path=/manage

management.port=XXX    #指定管理端口

management.address=X.X.X.X  #指定客户端ID

原文地址:https://www.cnblogs.com/funnyboy0128/p/8047533.html