如何在 Spring Boot Actuator 中自定义 `SessionFactory` 健康指示器?
解读
国内一线互联网与金融企业普遍把 Actuator 健康端点作为 灰度发布、弹性扩缩容、告警阈值 的核心依据。默认的 DataSourceHealthIndicator 只能验证 JDBC 连通性,无法覆盖 Hibernate 二级缓存失效、连接池耗尽、方言不匹配 等 ORM 层特有故障。因此,面试官期望候选人能给出“可灰度、可回滚、可观测”的自定义方案,而不是简单抛一个 @Component 了事。关键点有三:
- 必须拿到 当前 Spring 容器管理的
SessionFactory,而非自行 new 一个; - 健康探测逻辑要 只读、轻量、幂等,禁止触发业务事件或写操作;
- 返回的
Health对象要包含 二级缓存命中率、待刷写队列长度、数据库方言版本 等 ORM 核心指标,方便 SRE 快速定位是“数据库问题”还是“Hibernate 问题”。
知识点
- Spring Boot Actuator 扩展机制:
HealthIndicator接口、CompositeHealthContributor、ReactiveHealthIndicator的自动发现规则。 - Hibernate 内部 SPI:
SessionFactoryImplementor、Statistics、CacheRegionStatistics、Metamodel,用于提取缓存、查询、连接池维度的实时指标。 - Spring ORM 抽象:
SessionFactoryUtils、HibernateExceptionTranslator,保证在健康检查失败时把异常转成DataAccessException,避免污染日志。 - 国内运维规范:健康端点必须 低于 50 ms RT,且 QPS 限流 10 倍于业务峰值;因此需要加
Resilience4j或Sentinel熔断,防止健康接口被刷爆。 - 安全合规:金融场景下
/actuator/health往往暴露给 内网 Prometheus + 网关,需配合management.endpoint.health.show-details=when-authorized以及 自定义 Keyhibernate的 role-based 授权。
答案
步骤一:定义只读探测工具类
public final class HibernateHealthProbe {
private final SessionFactoryImplementor sf;
HibernateHealthProbe(SessionFactoryImplementor sf) { this.sf = sf; }
Health health() {
Statistics stat = sf.getStatistics();
if (!stat.isStatisticsEnabled()) {
stat.setStatisticsEnabled(true); // 动态开启,无需重启
}
try (Session s = sf.openSession()) {
s.createNativeQuery("SELECT 1 FROM DUAL", Integer.class).getSingleResult();
} catch (Exception ex) {
return Health.down()
.withDetail("database", "connectivity fail")
.withException(ex)
.build();
}
return Health.up()
.withDetail("secondLevelCacheHitCount", stat.getSecondLevelCacheHitCount())
.withDetail("secondLevelCacheMissCount", stat.getSecondLevelCacheMissCount())
.withDetail("queryCacheHitCount", stat.getQueryCacheHitCount())
.withDetail("entityLoadCount", stat.getEntityLoadCount())
.withDetail("dialect", sf.getJdbcServices().getDialect().getClass().getSimpleName())
.build();
}
}
步骤二:注册自定义指示器并防止重复 Bean
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(SessionFactory.class)
@ConditionalOnEnabledHealthIndicator("hibernate")
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
public class HibernateHealthConfiguration {
@Bean
public HibernateHealthIndicator hibernateHealthIndicator(
@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
SessionFactoryImplementor sf = emf.unwrap(SessionFactoryImplementor.class);
return new HibernateHealthIndicator(new HibernateHealthProbe(sf));
}
}
步骤三:指示器实现
public class HibernateHealthIndicator implements HealthIndicator {
private final HibernateHealthProbe probe;
public HibernateHealthIndicator(HibernateHealthProbe probe) { this.probe = probe; }
@Override
public Health health() {
return probe.health();
}
}
步骤四:application.yml 加固
management:
endpoints:
web:
exposure:
include: health,metrics
endpoint:
health:
show-details: when-authorized
show-components: always
health:
defaults:
enabled: false # 关闭默认 DataSourceHealthIndicator,避免重复探测
通过以上四步,即可在 /actuator/health/hibernate 拿到 ORM 层专属健康报告,并支持 基于 SpEL 的告警规则:health.hibernate.status == 'DOWN'。
拓展思考
- 多租户 SaaS 场景:每个租户独立
SessionFactory时,可继承CompositeHealthContributor,把租户 ID 作为 命名空间前缀,实现 租户级精细化熔断。 - 云原生环境:将
HibernateHealthIndicator与 Kubernetes 探针 联动,利用/actuator/health/hibernate作为 readinessGate,当二级缓存命中率低于 80 % 时自动 摘除 Pod,避免缓存雪崩蔓延。 - 性能压测:在 全链路压测 期间,可临时把指示器升级为 ReactiveHealthIndicator,通过
Mono.fromCallable(() -> probe.health()).timeout(Duration.ofMillis(30))防止健康检查本身成为性能瓶颈。