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

Gatling如何在exec中手动评估EL表达式实现嵌套参数替换

方案1:使用ELCompiler手动完成表达式评估

你需要的ELCompiler导入路径是io.gatling.commons.el.ELCompiler,Gatling原生提供了该工具类直接解析EL字符串并结合Session完成变量替换,示例代码如下:

// 提前编译好两个body的EL表达式,不要放在exec内重复编译损耗性能
private val elCompiler = ELCompiler.default
private val body1El = elCompiler.compile[String](Source.fromResource("body1.json").mkString)
private val body2El = elCompiler.compile[String](Source.fromResource("body2.json").mkString)

val scn: ScenarioBuilder = scenario("Dynamic body")
  .feed(feeder)
  .exec(session => {
    val selectedBodyEl = if(session("requestType").as[String] == "first") body1El else body2El
    // 传入session完成评估,拿到变量替换后的完整请求体
    val evaluatedBody = selectedBodyEl(session).get
    session.set("request", evaluatedBody)
  })
  .exec(http("Http Call")
    .post(url)
    .body(StringBody("${request}"))
  )

注意:编译EL表达式的逻辑要放在场景定义外提前执行,不要放到session处理函数中每次请求重复编译。

方案2:更简洁的原生写法(无需手动处理EL)

你不需要额外存储request中间变量,直接给StringBody传入动态函数即可实现需求,Gatling会自动完成EL解析,代码更简洁:

val body1 = Source.fromResource("body1.json").mkString
val body2 = Source.fromResource("body2.json").mkString

val scn: ScenarioBuilder = scenario("Dynamic body")
  .feed(feeder)
  .exec(http("Http Call")
    .post(url)
    .body(StringBody(session => 
      if(session("requestType").as[String] == "first") body1 else body2
    ))
  )

这种写法下请求体内部嵌套的${uuid}等变量会被正常替换,不需要手动调用ELCompiler。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 18:54:06