Skip to content

SpringBoot 热部署与 Actuator

TIP

SpringBoot DevTools 提供开发时的热部署能力,Actuator 提供生产级的监控和管理端点。

DevTools 热部署

引入依赖

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

原理

DevTools 使用双 ClassLoader:

  • Base ClassLoader:加载不常变动的第三方 JAR
  • Restart ClassLoader:加载项目中自定义的类

当文件发生变化时,只重启 Restart ClassLoader(比冷启动快很多)。

配置

yaml
spring:
  devtools:
    restart:
      enabled: true           # 开启热重启
      additional-paths: src/main/java  # 额外监控路径
      exclude: static/**      # 排除不需要重启的路径
    livereload:
      enabled: true           # 开启 LiveReload

Actuator 监控

引入依赖

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

配置端点

yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env,loggers,threaddump
  endpoint:
    health:
      show-details: always
  server:
    port: 8081  # 用独立端口,不与业务端口冲突

常用端点

端点说明
/actuator/health健康检查
/actuator/info应用信息
/actuator/metrics指标信息
/actuator/env环境变量
/actuator/loggers日志级别(可动态修改)
/actuator/threaddump线程堆栈
/actuator/prometheusPrometheus 指标格式

自定义 Health Indicator

java
@Component
public class RedisHealthIndicator implements HealthIndicator {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Health health() {
        try {
            redisTemplate.opsForValue().get("health-check");
            return Health.up().build();
        } catch (Exception e) {
            return Health.down(e).build();
        }
    }
}

WARNING

生产环境务必对 Actuator 端点做安全防护,避免敏感信息泄露。