Thymeleaf 模板的缓存命中率是否可以通过 Actuator 的 /actuator/metrics 接口监控?

解读

面试官抛出这个问题,核心想验证三件事:

  1. 你是否真的在生产环境调优过 Thymeleaf,而不是停留在“会写 th:text”层面;
  2. 是否熟悉 Spring Boot Actuator 的指标扩展机制,能否把“业务层缓存”与“系统层监控”打通;
  3. 面对“官方没有现成指标”的场景,有没有造轮子的能力。

国内大厂(阿里、京东、美团)做前后端同构 SEO 时,Thymeleaf 模板动辄上千个,模板缓存命中率直接决定 Young GC 频率与首屏 RT,因此监控是刚需。回答时要把“官方不提供→如何自己埋点→如何暴露给 Actuator→如何验证”讲完整,才能体现落地经验。

知识点

  1. Thymeleaf 的缓存入口
    org.thymeleaf.cache.StandardCacheManager 内部持有 ConcurrentHashMap,模板缓存 key 为 TemplateCacheKey,value 为 CompiledTemplate。是否命中完全由 getTemplate 方法返回的 CacheEntry.isCacheHit() 决定。

  2. Spring Boot 的默认装配
    ThymeleafAutoConfiguration 只暴露了 spring.thymeleaf.cache=true/false,并未注册任何 MeterBinder,因此 /actuator/metrics 里默认找不到 thymeleaf.* 指标。

  3. Actuator 自定义指标套路
    实现 MeterBinder 接口 → 注入 MeterRegistry → 在构造方法里把 CacheStatistics 注册成 Gauge/FunctionCounter;也可直接继承 CacheMetricsRegistrarConfiguration 的套路,把 Thymeleaf 的 Cache 包装成 Spring 的 ConcurrentMapCache,再复用 CacheMetrics。

  4. 指标命名规范
    国内公司对标 Prometheus 规范,推荐命名模板:thymeleaf_template_cache_hits_total、thymeleaf_template_cache_misses_total,带上 tag=“templateResolverName” 以便多引擎拆分。

  5. 观测验证
    本地使用 http://localhost:8080/actuator/metrics/thymeleaf.template.cache 能看到命中/未命中数值;压测 1 w 并发后,命中率若低于 95%,即可触发告警并联动扩容或预热。

答案

默认情况下,/actuator/metrics 里并没有 Thymeleaf 模板缓存的任何指标,因为 Spring Boot 只帮我们把 Thymeleaf 的 CacheManager 装配到 IOC,却未注册对应的 MeterBinder。
要监控命中率,必须自己扩展:

  1. 自定义一个 ThymeleafCacheMetrics,实现 MeterBinder,在 bindTo 方法里把 StandardCacheManager 的统计值(hits/misses)映射成 Gauge;
  2. 把该 Metrics 类声明成 @Component,随应用启动自动注册到 MeterRegistry;
  3. 打开配置 management.metrics.export.prometheus.enabled=true,即可在 /actuator/metrics/thymeleaf.template.cache 中看到 hits、misses、hit_ratio 三个指标;
  4. 若公司用 Prometheus + Grafana,可预置告警规则:hit_ratio < 0.95 持续 5 min 即@相关负责人,同时触发模板预热脚本。

通过以上四步,就能把 Thymeleaf 缓存命中率无缝接入 Spring Boot 的可观测体系,实现与 JVM、Tomcat、HikariCP 指标同屏对比,满足国内生产环境 7×24 监控需求。

拓展思考

  1. 如果项目使用多模板引擎(Thymeleaf + Freemarker),如何统一抽象一个 TemplateCacheMetrics,避免每个引擎写一套 Binder?
  2. 在 Kubernetes 场景下,Sidecar 模式采集指标会带来 15s 延迟,如何把 Thymeleaf 缓存命中率下沉到 ServiceMesh(Istio)指标面,实现 sidecar 无侵入?
  3. 模板缓存命中率下降往往伴随“大对象”进入老年代,可结合 GC 日志做联合分析:当命中率低于 90% 且 CMS 晋升失败次数 > 3 时,自动扩容 Pod 并预热缓存,实现智能化弹性。