You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gatling Java API中为每个请求添加随机correlation-id请求头

解决Gatling Java API中请求头correlation-id值固定的问题

问题原因

你当前的代码里,"test-" + UUID.randomUUID()是在Simulation类初始化阶段就执行完毕的,生成的是一个固定字符串。后续所有请求都会复用这个预先生成的值,自然不会每次请求都生成新的correlation-id。

解决方案

Gatling提供了动态生成请求头的机制,需要让UUID在每次请求执行时才生成,而非场景构建阶段。以下两种方式都可以实现:

方式一:直接通过函数动态生成

利用Gatling的header方法支持Expression<String>类型参数的特性,传入一个从Session生成UUID的函数:

ScenarioBuilder scn = scenario("RecordedSimulation")
  .exec(
    http("request_0")
      .post("/getorder")
      .headers(headers_0)
      .header("correlation-id", session -> "test-" + UUID.randomUUID())
      .body(RawFileBody("recordedsimulation/0000_request.json"))
  );

方式二:先存入Session再引用

如果后续请求需要复用同一个correlation-id,可以先将生成的值存入Session,再通过Gatling表达式语言引用:

ScenarioBuilder scn = scenario("RecordedSimulation")
  // 先生成UUID并存入Session
  .exec(session -> session.set("correlationId", "test-" + UUID.randomUUID()))
  .exec(
    http("request_0")
      .post("/getorder")
      .headers(headers_0)
      // 通过表达式引用Session中的值
      .header("correlation-id", "#{correlationId}")
      .body(RawFileBody("recordedsimulation/0000_request.json"))
  );

内容的提问来源于stack exchange,提问作者Jerald Baker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:55:19