SpringBoot正确、安全地关闭服务_晏霖/胖虎的博客-CSDN博客_springboot 关闭服务

前言

我们利用远程关闭功能可以实现优雅地关闭指定地服务。

正文

本文依然使用v1.5.8.RELEASE ,讲地是利用actuatorEndpoints实现关闭服务

首先准备一个eureka服务,然后启动他。

然后准备一个eureka客户端服务,客户端的pom除了必要的springboot的web依赖还需要添加依赖如下

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

在eureka客户端服务的application.properties文件开启shutdown endpoint,SpringBoot的endpoints.shutdown.enabled默认是关闭的。

eureka.client.service-url.defaultZone=http://admin:admin@localhost:1111/eureka/server.port=8762spring.application.name=eureka-client#启用shutdownendpoints.shutdown.enabled=true#禁用密码验证endpoints.shutdown.sensitive=false #如果用的2.x版本的 就用注释的那四行配置#management.endpoints.shutdown.enabled=true#management.endpoints.health.enabled=true#management.endpoints.web.base-path=/#management.endpoints.web.exposure.include=*

配置已经配好,这时可以启动服务了,将他注册在eureka上面,这时我们可以看到下面

然后在终端执行 curl -X POST 127.0.0.1:8762/shutdown ,可以看到message:Shutting down,bye...说明成功关闭了服务

下面笔者要教给大家一种高级使用的方法,做了一个安全的认证,上面关闭服务的缺点大家显而易见,知道服务端口和ip的就能关闭,这种做法很不安全,接下来要在客户端服务配置一下安全认证。

首先在eureka客户端服务的application.properties文件追加配置

eureka.client.service-url.defaultZone=http://admin:admin@localhost:1111/eureka/server.port=8762spring.application.name=eureka-clientmanagement.security.enabled=true#启用shutdownendpoints.shutdown.enabled=true#禁用密码验证endpoints.shutdown.sensitive=true#验证用户名security.user.name=admin#验证密码security.user.password=admin#角色management.security.role=SUPERUSER#指定shutdown endpoint的路径endpoints.shutdown.path=/custompath#也可以统一指定所有endpoints的路径`management.context-path=/manage`#指定管理端口和IPmanagement.port=8081management.address=127.0.0.1

我们使用了security,就需要在pom添加依赖

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

大功告成,是不是很简单,下面启动你的客户端服务,这里我就不贴一些多余的图片了,成功注册到eureka上面了,和上面的图一样。

接下来使用终端访问 curl -X POST -u admin:admin 127.0.0.1:8081/custompath

看见了你的服务又和你say byebye了吧! 

这个命令  curl -X POST -u admin:admin 127.0.0.1:8081/custompath  每一个位置对应的参数值大家可以看application.properties文件分别对应了哪些配置就明白了。

路过的大佬,看到这里给个赞吧!


原网址: 访问
创建于: 2021-08-12 14:59:47
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论