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

Gatling Session API使用疑问:遍历JSON响应提取指定国家代码对应ID时Session赋值失效问题咨询

解决Gatling中Session更新不生效的问题:遍历JSON响应存储目标ID

你遇到的问题核心在于Gatling的Session是不可变对象,这是很多Gatling新手容易踩的坑。让我一步步帮你分析和解决:

问题原因拆解

你的代码里,当找到countryCode == "PL"的项时,调用了session.set("offerId", itemMap("offerId")),但这个方法并不会修改原来的Session实例——它会返回一个包含新属性的全新Session对象。而你最后还是返回了原来的session变量,导致所有修改都被丢弃了。

当你最后打印session("offerId")时,因为这个属性从来没在原始Session里被设置过,Gatling的Session API在找不到属性时可能出现意外输出(比如你看到的"item",大概率是Session里其他变量的干扰),但本质是你的修改根本没生效。

另外,你的代码里还有个小笔误:itemMap("offerd")应该是itemMap("offerId"),这个也要修正哦。

修正后的手动遍历代码

把你的session处理逻辑改成这样,确保返回修改后的Session:

def getOffer() = {
 exec( 
  http("GET /offer")
  .get("/offer")
  .check(status.is(Constant.httpOk))
  .check(jsonPath("$[*]").ofType[Map[String,Any]].findAll.saveAs("offerList")))
 .foreach("${offerList}", "item"){
  exec(session => {
   val itemMap = session("item").as[Map[String,Any]]
   val countryCodeId = itemMap("countryCode").toString // 显式转String避免类型匹配问题
   println("****" + countryCodeId)
   if (countryCodeId == "PL"){
    val targetOfferId = itemMap("offerId")
    println("*************"+ targetOfferId)
    // 创建新的Session并赋值,然后返回这个新Session
    val updatedSession = session.set("offerId", targetOfferId)
    println("$$$$$$$$$$$$$$" + updatedSession("offerId"))
    updatedSession
   } else {
    // 不满足条件时返回原始Session
    session
   }
  })
 }
}

更简洁的Gatling原生写法

其实你完全不用手动遍历Session,Gatling的jsonPath支持条件过滤,可以直接提取符合条件的offerId,代码更简洁也更高效:

def getOffer() = {
 exec( 
  http("GET /offer")
  .get("/offer")
  .check(status.is(Constant.httpOk))
  // 直接用jsonPath的条件表达式找到countryCode为PL的项的offerId
  .check(jsonPath("$[?(@.countryCode == 'PL')].offerId").find.saveAs("offerId"))
 )
 // 之后就可以直接用${offerId}调用这个值了
 .exec(session => {
  println("存储的offerId:" + session("offerId").as[String])
  session
 })
}

这种写法利用了Gatling内置的JSON解析能力,避免了手动处理Session不可变性的问题,是更推荐的Gatling风格写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:27:31