问题描述
我在gatling模拟中使用了2个API调用。一个API返回第二个的身份验证令牌,因此我只需要在执行过程中调用一次令牌生成API调用,并在整个执行过程中将其生成的令牌用于第二个API。但这仅适用于执行的第一个周期,而我保存的令牌没有被其余的执行使用。
object KeycloakToken extends CMS {
def request(conf: ExecutionConfig): HttpRequestBuilder = {
http("Get Auth token from Keycloak")
.post(s"${conf.authUrl}/token")
.body(StringBody(""" {
"realm": "realm","clientId": "clientId","clientSecret": "clientSecret","grantType": "urn:ietf:params:oauth:grant-type:token-exchange","userName" : "userName"
} """)).asJson
.check(jsonPath("$.access_token").saveAs("token"))
}
}
object getoffers extends CMS {
def request(conf: ExecutionConfig): HttpRequestBuilder = {
http("getoffers")
.post(s"$context")
.body(StringBody(""" Body """)).asJson
.headers(headers)
.header("Authorization",s => s"Bearer ${s.attributes("token")}")
.check(jsonPath("$.data.offers.offers[0].id").exists)
}
}
execute.apply(
scenario("service")
.exec(session => session.set("counter",myGlobalVar.getAndIncrement))
.doIf(session => session("counter").validate[Int].map(i => i == 0)) {
exec(KeycloakToken.request(conf)) //--call only once
}
.exec(getoffers.request(conf))
)
解决方法
加特林会话对象对于每个用户都是唯一的。因此,当您将counter
会话变量设置为场景的第一步时,如果counter == 0,则仅使用要执行的第一个用户尝试使用doIf
来获取令牌。
由于会话对该用户是唯一的,因此其他任何用户的会话对象中都没有token
的值。
您尝试做的事情似乎是一个很常见的问题-发出一个请求以获取某种数据,然后在所有用户之间共享这些数据。例如:here
请注意,一旦加倍3.4,looks like这种情况就会更容易