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

Gatling RandomSwitch稳定性压测时产品名称重复问题求助

问题:Gatling稳定性压测1小时后出现产品名称重复校验错误

我使用Gatling的RandomSwitch进行稳定性压测,压测场景代码如下:

ScenarioBuilder getScenario2(){
        return scenario("Scenario").exec(getAuthenticationChain())
                .randomSwitch().on(
                        new Choice.WithWeight(58.00636267, exec(getCreateProductASyncChain(10, "S1"))),
                        new Choice.WithWeight(7.246376812, exec(getCreateProductAsyncChain(30, "S2"))),
                        new Choice.WithWeight(3.817603393, exec(getCreateProductAsyncChain(50, "S3"))),
                        new Choice.WithWeight(4.91339696, exec(getCreateProductAsyncChain(70, "S4"))),
                        new Choice.WithWeight(2.47437257, exec(getCreateProductAsyncChain(90, "S5"))),
                        new Choice.WithWeight(2.721809827, exec(getCreateProductAsyncChain(110, "S6"))),
                        new Choice.WithWeight(1.590668081, exec(getCreateProductAsyncChain(130, "S7"))),
                        new Choice.WithWeight(19.22940969, exec(getCreateProductAsyncChain(150, "S8")))
                        );
    }

其中getCreateProductASyncChain方法用于构建请求链:

ChainBuilder getCreateProductASyncChain(int productCount, String name){
        String createProducString = getCreateProductRequestString(productCount, "SYNC");
        return exec(
                http("CreateProducts")
                        .post(graphQlUrl)
                        .header("Authorization", " #{Authorization}")
                        .header("cookie", "#{cookie}")
                        .header("Content-Type", "application/json")
                        .body(StringBody(createProducString))
                        .check(status().is(200))
                        .check(bodyString().saveAs("responseBody"))
                        .check(jsonPath("$['data']['content']['content_obj']['status']").in( "success", "error"))
                        .check(jsonPath("$['data']['content']['content_obj']['status']").saveAs("status"))
                        .check(jsonPath("$['data']['content']['content_obj']['id']").saveAs("id")))
        
                .exec(session -> {
                    System.out.println("Response Body:****************************"+session.getString("responseBody"));
                    
                    return session;
                });
    }

在getCreateProductRequestString方法中,我通过java.util.UUID.randomUUID()生成产品名称,每个请求会创建productCount个产品JSON对象:

for (int i=0; i<count; i++){
            productSb.append("{\"name\": \"Test_prd "+java.util.UUID.randomUUID()+"\"}")
            
        }

当前问题:压测运行15分钟及以内正常,但运行1小时时会出现产品名称重复,触发API的校验错误。


解决思路与方案

1. 核心问题定位

原代码中getCreateProductRequestString是在场景初始化阶段生成请求体,而非每个请求执行时动态生成。这意味着所有虚拟用户的请求会复用同一批UUID,长时间压测下必然出现重复。

2. 修正请求体生成时机

将产品名称的生成逻辑移到每个请求执行阶段,确保每次请求都生成全新的UUID:

ChainBuilder getCreateProductASyncChain(int productCount, String name){
    // 先在会话中生成唯一的产品列表
    return exec(session -> {
        StringBuilder productSb = new StringBuilder();
        for (int i=0; i<productCount; i++){
            if (i > 0) productSb.append(",");
            // 每次循环生成新的UUID
            String uniqueProductName = "Test_prd_" + java.util.UUID.randomUUID();
            productSb.append("{\"name\": \"" + uniqueProductName + "\"}");
        }
        return session.set("productList", productSb.toString());
    })
    .exec(
            http("CreateProducts")
                    .post(graphQlUrl)
                    .header("Authorization", " #{Authorization}")
                    .header("cookie", "#{cookie}")
                    .header("Content-Type", "application/json")
                    // 使用会话中的动态生成的产品列表
                    .body(StringBody("{\"query\": \"mutation { createProducts(products: [#{productList}]) }\"}"))
                    .check(status().is(200))
                    .check(bodyString().saveAs("responseBody"))
                    .check(jsonPath("$['data']['content']['content_obj']['status']").in( "success", "error"))
                    .check(jsonPath("$['data']['content']['content_obj']['status']").saveAs("status"))
                    .check(jsonPath("$['data']['content']['content_obj']['id']").saveAs("id")))
    .exec(session -> {
        System.out.println("Response Body:****************************"+session.getString("responseBody"));
        return session;
    });
}

3. 进一步降低重复概率(可选)

若担心UUID仍有极低概率重复,可结合时间戳、线程ID等信息增强唯一性:

String uniqueProductName = String.format("Test_prd_%s_%d_%d",
        java.util.UUID.randomUUID(),
        System.currentTimeMillis(),
        Thread.currentThread().getId());

4. 添加重试机制(可选)

针对偶尔出现的重复错误,可配置自动重试避免影响压测结果:

// 在请求后添加重试逻辑
.retry(2) // 最多重试2次
.retryWhen(session -> "error".equals(session.getString("status")));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:12:04