0
点赞
收藏
分享

微信扫一扫

spring优雅关机

祈澈菇凉 2023-08-02 阅读 89

优雅关机的意思是收到关机命令之后, 不再处理新请求,处理完已接收的请求之后再关机. 避免了正在处理中的请求突然终止引起的数据不一致等奇怪的错误.  

  • 需要Tomcat 版本>=9.0.33 
  • ctrl+c 或 kill -2 方式停止应用时优雅关机有效,kill -9 时失效

增加如下配置:

# 启动优雅关机
server.shutdown=graceful
# 优雅关机之后多久强制关机
spring.lifecycle.timeout-per-shutdown-phase=20s

测试过程: 使用如下代码, 请求'/graceful', 等待5s之后关闭app, 发现app会在正常响应ok之后才关闭:

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;


@SpringBootApplication
@EnableCaching
@Slf4j
@RestController
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @GetMapping("graceful")
    public String testGraceful() throws InterruptedException {
        TimeUnit.SECONDS.sleep(10);
        return "ok";
    }

    //    kill -2 ,ctrl+c 推出应用时会执行,kill -9 不执行
    //    docker stop时未知
    @PreDestroy
    public void preDestroy() {
        // 回收资源
        log.info("回收资源完毕");
    }
}

优雅关机日志:

spring优雅关机_java

举报

相关推荐

0 条评论