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

Gatling中如何将Feeder数据传递给自定义函数?解决Session变量传递至自定义方法的问题

解决Gatling中Session变量传递给自定义FireClient方法的问题

看起来你遇到的核心问题是没搞清楚Gatling的延迟执行表达式模型,以及如何正确把自定义请求方法接入Gatling的执行链。我来一步步帮你解决:

问题根源分析

  1. 直接拼接Expression对象导致的错误:你最初的代码里,把deliveryId(一个Expression[String]对象)直接拼接到URI字符串里,得到的是对象的toString结果(就是你看到的io.gatling.core.session.el.ElCompiler$$$Lambda...),因为Gatling的Expression是延迟计算的,只有在Session上下文里才会解析成真实值。
  2. 在Session函数中调用方法的错误:你尝试在exec { session => ... }里直接调用AdminClient.getDeliveryStateByDeliveryId(),但这个代码块只是处理Session,并没有把返回的HttpClientRequest加入到Gatling的执行链中,所以Gatling认为没有发送任何请求,自然会报错。

正确解决方案

方案1:直接在自定义方法中引用Session变量(最简单)

如果你的Session变量名固定是delivery_uuid,可以直接在自定义方法里用Gatling的EL表达式引用它,不需要额外传递参数:

object AdminClient extends FireClient {
  def getDeliveryStateByDeliveryId(name: String = "Get delivery state by ID") : HttpClientRequest = {
    get(name)
      // 直接用Gatling的EL表达式从Session中取值
      .uri("/url/${delivery_uuid}")
      .requestModeAdmin
      .allowOkStatus
  }
}

对应的场景代码简化成:

object LoadTest extends FireScenarios {
  val csvFeeder = csv("deliveries.csv")
  fireScenario("Load test starts")(_
    .feed(csvFeeder)
    // 直接调用方法,Gatling会自动从Session中解析delivery_uuid
    .exec(AdminClient.getDeliveryStateByDeliveryId())
  )
}

方案2:支持动态传递Session变量名(更灵活)

如果需要支持不同的Session变量名,可以让方法接收变量名参数,然后通过Session上下文动态构建URI:

object AdminClient extends FireClient {
  def getDeliveryStateByDeliveryId(
    name: String = "Get delivery state by ID",
    deliveryIdSessionKey: String = "delivery_uuid"
  ) : HttpClientRequest = {
    get(name)
      // 从Session中根据key获取真实值,再构建URI
      .uri(session => s"/url/${session(deliveryIdSessionKey).as[String]}")
      .requestModeAdmin
      .allowOkStatus
  }
}

调用时可以指定自定义key:

.exec(AdminClient.getDeliveryStateByDeliveryId(deliveryIdSessionKey = "custom_delivery_id"))

方案3:传递Expression参数(最贴合你最初的尝试)

如果你坚持要传递Expression[String]参数,需要用Gatling的map方法解析这个表达式,再构建URI:

object AdminClient extends FireClient {
  def getDeliveryStateByDeliveryId(
    name: String = "Get delivery state by ID",
    deliveryId: Expression[String] = "${delivery_uuid}"
  ) : HttpClientRequest = {
    get(name)
      // 解析Expression得到真实ID,再拼接URI
      .uri(deliveryId.map(id => s"/url/$id"))
      .requestModeAdmin
      .allowOkStatus
  }
}

这样调用时,无论是传EL表达式字符串"${delivery_uuid}",还是自定义的Expression,都能正确解析成真实值。

关键注意点

  • 永远不要直接拼接Expression对象到字符串:Gatling的Expression是一个函数,只有在Session上下文里执行才会得到真实值,必须通过Gatling提供的API(比如uri的Expression重载、map方法)来处理。
  • 自定义方法必须返回可执行的请求对象:要确保你的方法返回HttpClientRequest,并且直接在exec中调用,这样Gatling才会把它加入到执行链中,不要在exec { session => ... }里调用后丢弃返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:22:37