如何使用 JMeter 或 Gatling 对 Thymeleaf 模板进行高并发压测?

解读

面试官问“如何压测 Thymeleaf”,并不是让你去压测模板文件本身,而是考察你是否能把“模板渲染”这一环节纳入整个 Spring Boot Web 链路的性能基线。国内大多数公司把 Thymeleaf 当作服务端渲染(SSR)方案,压测目标通常有三类:

  1. 纯模板渲染耗时(CPU 密集)
  2. 模板+DB 的完整 QPS(IO 叠加 CPU)
  3. 模板缓存命中率对 GC 的影响

因此,回答必须同时覆盖“压测脚本设计、指标采集、瓶颈定位、调优闭环”四个维度,并给出可落地的国产中间件栈(Spring Boot 2.7.x + Thymeleaf 3.0.x + Druid + RocketMQ 等)下的实操细节。

知识点

  1. Thymeleaf 渲染链路
    请求 → DispatcherServlet → ThymeleafViewResolver → TemplateEngine → IResourceResolver → 解析 AST → 合并 Context → 输出 Writer
    其中“解析 AST”最耗 CPU,模板缓存(spring.thymeleaf.cache=true)决定是否每次重新解析。

  2. 压测工具选型
    JMeter:国内团队熟悉,GUI 调试方便,支持阶梯线程组、Redis 监听器、后端监听器对接 InfluxDB+Grafana。
    Gatling:基于 Netty+NIO,单机并发高,Scala DSL 写脚本,CI 友好,适合云原生流水线。

  3. 关键指标

    • 服务端:RT、QPS、CPU、线程上下文切换、模板缓存命中率、GC 次数/暂停时间、Code Cache 占用。
    • 网络:TTFB(首字节时间)、传输体积(HTML 压缩后)。
    • 错误:5xx、4xx、Thymeleaf 解析异常(TemplateProcessingException)。
  4. 国内常见坑

    • 忘记关闭 Spring Boot DevTools,导致缓存失效,压测结果失真。
    • 使用 Nginx 反向代理时,未开启 gzip_static,传输体积翻倍。
    • 阿里云 ECS 小规格实例,单核 CPU 被模板渲染打满,误以为是 Thymeleaf 性能差。

答案

(以下给出可直接落地的“JMeter 方案”和“Gatling 方案”,任选其一即可讲清思路)

一、JMeter 方案

  1. 脚本设计
    a. 线程组:阶梯线程,5 min 内从 0 并发涨到 500 并发,持续 10 min,再阶梯下降。
    b. HTTP 取样器:

    • 首页 /index:模板含 10 条 DB 列表,测试“模板+DB”。
    • 纯静态 /about:模板无变量,测试“纯渲染”。
      c. 参数化:使用 CSV 配置 100 条商品 ID,避免缓存击穿。
      d. 断言:响应文本包含 <html lang="zh-CN">,确保模板渲染成功。
  2. 监控对接

    • 后端监听器: influxdb-url 填公司内网 InfluxDB(192.168.x.x:8086),measurement=thymeleaf_jmeter,对接 Grafana 看板。
    • 服务器 agent:部署 prometheus-jmx-exporter,采集 JVM 指标,重点看 thymeleaf_cache_hits_total。
  3. 瓶颈定位

    • CPU 飙高:Arthas 执行 profiler start --event cpu,火焰图发现 org.thymeleaf.engine.TemplateManager.process 占比 68%,确认模板解析热点。
    • GC 频繁:GC 日志显示 5s 一次 Young GC,Survivor 区过小,调大 -Xmn1g -XX:SurvivorRatio=8 后 QPS 提升 18%。
  4. 调优闭环

    • 开启模板缓存:spring.thymeleaf.cache=true,重启后同一 URL 压测,QPS 从 1200 提升到 4200,RT 从 180 ms 降到 45 ms。
    • 使用 Decoupled Logic:把 th:replace 片段拆成独立模板,减少 AST 节点 30%,CPU 下降 8%。
    • 压缩输出:server.compression.enabled=true,HTML 体积减少 70%,带宽节省 3 Mbps。

二、Gatling 方案

  1. 脚本核心(Scala)
val httpProtocol = http.baseUrl("http://10.0.0.100:8080")
  .acceptEncodingHeader("gzip, deflate")

val scn = scenario("ThymeleafSSR")
  .feed(csv("productId.csv").random)
  .exec(http("search")
    .get("/product/${id}")
    .check(status.is(200), substring("th:utext")))

setUp(scn.inject(
  incrementUsersPerSec(50)
    .times(10)
    .eachLevelLasting(30 seconds)
    .separatedByRampsLasting(10 seconds)
)).protocols(httpProtocol)
  1. 指标采集

    • Gatling 默认生成 global_stats.json,通过 Jenkins Plot 插件把 mean RT 与 95 pct RT 纳入质量门禁:meanRT < 50 ms 且 95pctRT < 150 ms 才算通过。
    • 同时把 simulation.log 解析到 Elasticsearch,研发大屏实时对比不同版本模板性能回归。
  2. 调优案例

    • 发现 95pctRT 偶发 400 ms,链路追踪(SkyWalking)显示 Thymeleaf 等待数据库连接池 60 ms;把 Druid maxPoolSize 从 20 调到 50,长尾消失。
    • 模板里误用 #dates.format(${instant}, 'yyyy-MM-dd HH:mm:ss') 每次 new SimpleDateFormat,造成锁竞争;改为 #temporals.format(${instant}, 'yyyy-MM-dd HH:mm:ss') 使用 DateTimeFormatter 线程安全,CPU 下降 5%。

拓展思考

  1. 如果公司后续把 Thymeleaf 页面静态化到 OSS+CDN,压测重心会转向“缓存失效瞬间”的并发回源,可用 Gatling 的 constantConcurrentUsers(2000) 模拟突发流量,验证 Spring Boot 的 ScheduledThreadPoolExecutor 队列是否会打满。
  2. 在 Kubernetes 环境,可把模板渲染 Pod 的 HPA 阈值从 CPU 60% 改为“QPS 5000/单 Pod”作为自定义指标,通过 Prometheus Adapter 实现秒级弹性,压测脚本需配套 kubectl top pod 验证扩容效果。
  3. 若业务需要国际化(i18n),模板里大量使用 #{msg.key},压测时要构造不同 Accept-Language 头,观察 MessageSource 的 LRU 缓存命中率,避免每次重新加载 properties 文件导致 RT 抖动。