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

如何在Gatling中从Session传递Map元素到每个请求?

Gatling 动态替换JSON模板 & forEach循环执行说明

一、合并Map列表到Session(补充验证)

先确认你合并列表的代码逻辑是否正确,这里给个标准实现示例:

exec(http("查询接口")
  .get("/api/query")
  .check(jsonPath("$..uniqueId").findAll.saveAs("uniqueIdList"))
  .check(jsonPath("$..deptId").findAll.saveAs("deptIdList")))
.exec(session => {
  val uniqueIds = session("uniqueIdList").as[Seq[String]]
  val deptIds = session("deptIdList").as[Seq[String]]
  // 按索引合并为Map列表,需确保两个列表长度一致
  val dataList = uniqueIds.zip(deptIds).map { case (uid, did) =>
    Map("uniqueId" -> uid, "deptId" -> did)
  }
  session.set("dataList", dataList)
})

二、用Session中的Map列表替换JSON模板字段

假设你的assign-data.json模板内容如下:

{
  "uniqueId": "${uniqueId}",
  "deptId": "${deptId}",
  "otherFixedField": "staticValue"
}

方法1:forEach + ElFileBody 结合

直接遍历Session中的dataList,每次循环将当前Map的键值对注入Session,再用模板文件自动替换字段:

foreach("${dataList}", "currentItem") {
  exec(session => {
    val item = session("currentItem").as[Map[String, String]]
    // 将当前Map的所有键值对存入Session
    session.setAll(item)
  })
  .exec(http("执行更新")
    .post("/api/update")
    .body(ElFileBody("assign-data.json")).asJson)
}

每次循环时,${uniqueId}和${deptId}会自动读取Session中的对应值完成替换。

方法2:动态构建请求体(无需模板文件)

如果不想依赖外部JSON文件,可直接用StringBody动态生成请求内容:

foreach("${dataList}", "currentItem") {
  exec(http("执行更新")
    .post("/api/update")
    .body(StringBody(session => {
      val item = session("currentItem").as[Map[String, String]]
      s"""{
         |  "uniqueId": "${item("uniqueId")}",
         |  "deptId": "${item("deptId")}",
         |  "otherFixedField": "staticValue"
         |}""".stripMargin
    })).asJson)
}

三、forEach循环的执行范围说明

forEach嵌套exec的写法,每个虚拟用户都会独立完整遍历自己Session中的dataList:

  • 每个用户从查询接口拿到专属的uniqueIdList和deptIdList,合并成自己的dataList
  • 进入循环后,该用户会依次遍历列表中的每一个Map,执行循环内的所有exec步骤(比如发送更新请求)
  • 不同用户的循环流程完全独立,互不干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:52:16