springboot 2.x 如何优雅的停止服务

一般的使用tomcat启动项目,会使用shutdown.sh才停止。但是在springboot中tomcat内置了。
所以一般的要关掉项目会使用kill -9 pid 来杀死进程,再进行启动。这样会有弊端,如果还有线程在执行任务,这一刻会立即停止,严重的情况下会丢失数据。那么如何优雅的关闭呢?

springboot集成actuator 可完美解决。

1.加入actuator jar包

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

2.在application.properties/application.yml中加入配置
management.endpoint.shutdown.enabled=true
management.endpoints.web.exposure.include=shutdown
3.启动项目
在linux系统中执行一下代码
url -X POST http://host:port/actuator/shutdown
host 代表 服务的地址
port 代表 服务的端口

如果收到以下信息表示关闭成功

{
    "message": "Shutting down, bye..."
}

4.上面的有一个弊端 如果别人知道了ip地址和端口号就能远程操作你的服务了,怎么解决呢
在application.properties或application.yml中加入

#自定义管理端点的前缀(保证安全)
management.endpoints.web.base-path=/MyActuator
#自定义端口
management.server.port=12581(不能和你的tomcat服务器端口号一样)
#不允许远程管理连接(不允许外部调用保证安全)
management.server.address=127.0.0.1

这样访问地址就变成这样了
curl -X POST http://127.0.0.1:12581/MyActuator/shutdown

5.如果这样还不够安全可以结合 spring security
1.加入 spring security jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2. 加入用户名和密码
```

  spring.security.user.name=actuator
 
 spring.security.user.password=123456
 ```

3.加入 spring security config

@Configuration
public class ActuatorWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.csrf().disable().authorizeRequests().antMatchers("/").permitAll()
              .requestMatchers(EndpointRequest.toAnyEndpoint()).authenticated().and()
              //开启basic认证,若不添加此项,将不能通过curl的basic方式传递用户信息
              .httpBasic();
  }

/**
如果有swagger 并且想排除swagger的可以加入下面的代码
*/
  @Override
  public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/swagger-ui.html")
              .antMatchers("/webjars/springfox-swagger-ui/**")
              .antMatchers("/swagger-resources/**")
              .antMatchers("/v2/api-docs");
  }

}

4.执行新的命令
curl -X POST -u user:password http://host:port/actuator/shutdown

最后执行
curl -X POST -u actuator:123456 http://host:port/actuator/shutdown

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值