Spring Cloud微服务 优雅停止

2017-02-17 20:29

优雅停止服务

Spring Boot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行、产品级别的基于Spring框架的应用,大部分Spring Boot应用只需要非常少的配置就可以快速运行起来,是一个与微服务(MicroServices)相当契合的微框架。
spring-boot-starter-actuator中提供了/shutdown的方式来优雅的停止服务

pom.xml配置:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath/>
</parent>

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

application.properties配置:

# 启用shutdown
endpoints.shutdown.enabled=true

# 禁用密码验证
endpoints.shutdown.sensitive=false

服务启动后,可以通过linux的curl命令发送POST请求的方式优雅的停止服务。

curl -X POST host:port/shutdown
{"message":"Shutting down, bye..."}

服务停止log

c.n.e.EurekaDiscoveryClientConfiguration : Unregistering application eureka-server with eureka with status DOWN
com.netflix.discovery.DiscoveryClient    : Shutting down DiscoveryClient ...
com.netflix.discovery.DiscoveryClient    : Completed shut down of DiscoveryClient
o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans
c.n.eureka.DefaultEurekaServerContext    : Shutting down ...
c.n.eureka.DefaultEurekaServerContext    : Shut down
o.apache.catalina.core.StandardService   : Stopping service Tomcat
o.a.c.c.C.[Tomcat].[localhost].[/]       : Destroying Spring FrameworkServlet 'dispatcherServlet'