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

Gatling中session.set与feed结合使用时变量未正确替换的问题求助

解决Gatling中Session.set与Feed变量替换异常的问题

问题核心

你遇到的问题是:在Gatling场景中,通过session.set("pTypeSymbol", "${pEqSymbol}")设置的变量,并没有被替换为Feed中的实际值,而是保留了${pEqSymbol}字符串字面量。这是因为Gatling不会自动解析set方法中传入的字符串占位符,需要手动从Session中获取已存在的Feed值。

正确解决方案

修改Session设置的代码,直接从Session中提取pEqSymbol的实际值,而不是传入占位符字符串:

val getApiKeyScenario = scenario("getApiKey")
  .feed(getApiKeyData)
  .feed(pEqSymbolFeed)
  .feed(pOptionSymbol)
  .feed(pOtherSymbol)
  .exec(session => session
    .set("endPoint", "v1")
    .set("pTypeSymbol", session("pEqSymbol").as[String]) // 直接从Session获取Feed注入的值
    .set("authM", "&apikey=***********"))
  .exec(http("getApiKeyRequest")
    .get("/******/quotes-${endPoint}/quotes?source=rtbp&userid=test&symbol=${pTypeSymbol}${authM}")
    .check(status.is(200))
    .check(checkIf(doLogResponse) { bodyString.saveAs("pResponse") })
  )
  .doIf(doLogResponse) { logResponse() }

为什么之前的尝试失败?

  • 方法1:使用pEqSymbolFeed.readRecords.head("pEqSymbol")
    这种方式会直接读取Feed的第一条记录,破坏了Gatling Feed的迭代机制(每个虚拟用户应该按顺序获取Feed中的下一条记录),导致所有用户复用同一个值,甚至引发循环问题。

  • 方法2/3:使用s"${pEqSymbol}"或pEqSymbol.isDefined
    pEqSymbol是Session中的键名,不是Scala代码中的变量,所以编译器会提示not found: value pEqSymbol。Gatling的占位符${xxx}只能在支持EL(表达式语言)的上下文(比如HTTP请求的URL、headers等)中生效,在普通Scala代码中无法直接解析。

额外优化建议

如果pTypeSymbol只是作为中间变量传递pEqSymbol的值,其实可以直接在URL中使用${pEqSymbol},省去中间变量的设置,代码更简洁:

val getApiKeyScenario = scenario("getApiKey")
  .feed(getApiKeyData)
  .feed(pEqSymbolFeed)
  .feed(pOptionSymbol)
  .feed(pOtherSymbol)
  .exec(session => session
    .set("endPoint", "v1")
    .set("authM", "&apikey=***********"))
  .exec(http("getApiKeyRequest")
    .get("/******/quotes-${endPoint}/quotes?source=rtbp&userid=test&symbol=${pEqSymbol}${authM}") // 直接使用Feed变量
    .check(status.is(200))
    .check(checkIf(doLogResponse) { bodyString.saveAs("pResponse") })
  )
  .doIf(doLogResponse) { logResponse() }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:44:07