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

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

step1:pom引入spring boot Actoator依赖安全

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

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

endpoints.shutdown.enabled=true   #启用shutdown
endpoints.shutdown.sensitive=false  #须要禁用密码验证,不然须要进行认证才能调用服务
curl

step3:调用shutdown服务:spring-boot

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

 

经过上面的设置便可实现关闭spring boot应用,可是你会发现,这样会十分不安全,只要经过服务调用便可关闭应用,因此,具体应用中经常须要进行安全认证,好比借助Spring boot security,步骤以下:url

step1:pom.xml添加security依赖spa

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

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

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