一、什么是优雅关机
在最新的 spring boot 2.3 版本,内置此功能,不需要再自行扩展容器线程池来处理,目前 spring boot 嵌入式支持的 web 服务器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反应式和基于 Servlet 的 web 应用程序都支持优雅停机功能。我们来看下如何使用:
当使用 server.shutdown=graceful 启用时,在 web 容器关闭时,web 服务器将不再接收新请求,并将等待活动请求完成的缓冲期。
二、如何优雅关机
1、配置文件
# 优雅关机功能打开
server:
shutdown: graceful
# 设置应用缓冲时间
spring:
lifecycle:
timeout-per-shutdown-phase: 30s
2、新增Controller
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* 优雅宕机
*
* @return
*/
@ResponseBody
@RequestMapping(value = "/shutdown", method = RequestMethod.GET)
public CommonResult<String> shutdown(String userName, HttpServletRequest request) {
String ip = request.getRemoteAddr();
log.info("SystemController | shutdown userName={},ip={}", userName, ip);
Assert.isTrue(StringUtils.equalsIgnoreCase(userName, SystemConstants.SYSTEM_USER), "当前用户不正确,不可使用");
Assert.isTrue(StringUtils.equalsIgnoreCase(ip, CommonIpEnum.LOCALHOST.getValue()), "ip不正确,只能本机调用,不可使用");
ApplicationContext applicationContext = SpringUtil.getApplicationContext();
((ConfigurableApplicationContext) applicationContext).close();
return CommonResultBuilder.success("shutdown");
}