如何优雅重启java
优雅重启 Java 应用的方法
使用 Spring Boot Actuator
Spring Boot Actuator 提供 /actuator/restart 端点用于重启应用。需在 application.properties 中启用该功能:
management.endpoint.restart.enabled=true
调用方式:
curl -X POST http://localhost:8080/actuator/restart
通过外部脚本控制
创建启动脚本(如 restart.sh)实现平滑重启:
#!/bin/bash
kill -15 $(cat ./pidfile) # 发送SIGTERM信号
sleep 5
nohup java -jar yourapp.jar > /dev/null 2>&1 & echo $! > pidfile
使用 Java 内置信号处理
注册 JVM 关闭钩子实现优雅停机:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// 清理资源逻辑
System.out.println("执行清理操作");
}));
容器化部署方案
Docker 环境下可通过健康检查实现重启:
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost:8080/health || exit 1
配合编排工具(Kubernetes):
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
热部署工具(开发环境)
开发时可用 JRebel 或 Spring Boot DevTools:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
注意事项
- 确保所有线程池和连接池正确关闭
- 数据库事务需完整提交或回滚
- 分布式锁等资源需要主动释放
- 新版本应用应兼容旧版本数据格式




