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

如何在Gatling中从Feeder注入JSON至请求Body中

How to Inject JSON from Feeder into Request Body in Gatling

Got it, let's fix this up. The issue with your current code is that RawFileBody is meant to load static file content directly, but you need to dynamically generate a JSON body using the id value from your feeder. Here are two straightforward ways to achieve this:

Option 1: Use StringBody to Construct JSON Directly

Since your feeder provides an id value for each user, you can build the JSON body directly using Gatling's expression language to reference the feeder value:

.body(StringBody("""{"id":"${id}"}"""))

Triple quotes let you write the JSON string without escaping inner quotes, and ${id} pulls the current user's id from the feeder automatically.

Option 2: Use ElFileBody with a Template File

If you prefer keeping the JSON structure in a separate file (ideal for more complex bodies), create a template file (e.g., src/test/resources/json/gatling/request-template.json) with this content:

{"id":"${id}"}

Then reference this template in your request:

.body(ElFileBody("json/gatling/request-template.json"))

Gatling will replace the ${id} placeholder with the feeder's value for each user.

Full Modified Code

Here's your updated simulation class using Option 1 (swap in Option 2 if you prefer the template approach):

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class BasicSimulation extends Simulation {
  val httpConf = http
    .baseURL("http://localhost:8099")
    .headers(Map("Content-Type" -> "application/json"))
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-US,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")
    .userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")

  val feeder = jsonFile("src/test/resources/json/gatling/test.json")

  val scnPost = scenario("BasicSimulation")
    .feed(feeder)
    .exec(http("request_1")
      .post("/spring-test")
      // Use either StringBody or ElFileBody here
      .body(StringBody("""{"id":"${id}"}"""))
      .check(status.is(200)))

  setUp(
    scnPost.inject(constantUsersPerSec(3) during(3 seconds))
  ).protocols(httpConf)
}

How It Works

  • The .feed(feeder) step loads each entry from your JSON array into the user's session, making the id value accessible via ${id}.
  • Both StringBody and ElFileBody support Gatling's expression language, so they resolve the ${id} placeholder to the actual feeder value for every user request.

内容的提问来源于stack exchange,提问作者a.moussa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:11:05