用idea手动编写gatling脚本

键盘侠 2021年05月15日 1,005次浏览

目的

最近在做一些自动化和性能测试平台一些相关的东西,在做性能测试的时候之前大部分都是使用的是Jmeter作为测试引擎来做,但在有时候延迟高的应用中单机做大并发比较难,在此过程中注意到了有gatling这个工具,相关的一些特性和区别啥的就不列出来了,这里只是简单记录下初次使用时的一个示例.

必备条件

以下是我自己的运行环境

  • jdk8
  • scala sdk
  • idea 2021
  • maven

准备工作

准备本地的被测接口

  • 接口请求为
curl --location --request POST 'http://127.0.0.1/user/listAll' \
--header 'Content-Type: application/json' \
--data-raw '{
    "type":0
}'
  • 接口返回
{
    "code": 200,
    "msg": "操作成功",
    "data": [
        {
            "userId": "28f5433fa58f11ebaef90242ac110004",
            "account": "nidaye",
            "userName": "zx",
            "userPassword": "202cb962ac59075b964b07152d234b70",
            "type": "1",
            "mail": null,
            "phone": "13111112222",
            "lastLogin": null,
            "status": "0",
            "authority": "2",
            "creator": null,
            "createTime": "2021-04-25 06:26:25",
            "editor": null,
            "updateTime": "2021-04-25 06:26:25",
            "deleted": "0",
            "properties": null
        }
    ]
}

创建项目

在idea创建默认的mvn空项目

image.png

导入所需要依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bzlrobot.test</groupId>
    <artifactId>gatlingdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.gatling.highcharts</groupId>
            <artifactId>gatling-charts-highcharts</artifactId>
            <version>3.5.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>io.gatling</groupId>
                <artifactId>gatling-maven-plugin</artifactId>
                <version>3.1.1</version>
            </plugin>
        </plugins>
    </build>

</project>

编写简单的请求示例

package com.bzlrobot.test.tools.gatling

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

/**
 * @author: dsg
 *
 */
class UserQuerySimulation extends Simulation {

  val httpProtocol = http
    .baseUrl("http://127.0.0.1")
    .acceptHeader("application/json")

  val requestBody: String = "{\n    \"type\":0\n}"

  val scn = scenario("查询所有用户")
    .exec(http("开始查询用户")
      .post("/user/listAll")
      .header("Content-Type", "application/json")
      .check(status.is(200)) //断言返回状态码是否为200
      .check(jsonPath("$.msg").exists) //断言返回json中存在 msg 属性
      .body(StringBody(requestBody)))
    .pause(1)

  setUp(scn.inject(constantConcurrentUsers(100).during(1.minute))).protocols(httpProtocol)

}

运行测试

复制脚本

将编写好的UserQuerySimulation.scala复制到gatling的安装目录下

D:\APPS\GATLING-CHARTS-HIGHCHARTS-BUNDLE-3.5.1
├─bin
├─conf
├─lib
├─results
│  ├─userquerysimulation-20210515062448313
│  │  ├─js
│  │  └─style
│  ├─userquerysimulation-20210515063130439
│  │  ├─js
│  │  └─style
│  ├─userquerysimulation-20210515063455131
│  │  ├─js
│  │  └─style
│  └─userquerysimulation-20210515070338757
│      ├─js
│      └─style
├─target
│  └─test-classes
│      ├─com
│      │  └─bzlrobot
│      │      └─test
│      │          └─tools
│      │              └─gatling
│      └─computerdatabase
│          └─advanced
└─user-files
    ├─resources
    └─simulations
        └─computerdatabase
            └─advanced

这里的$gatling_DIR/user-files/simulations/computerdatabase/advanced目录下

开始执行

运行gatling.bat,在接下来的提示中选择我们自己的脚本[0] com.bzlrobot.test.tools.gatling.UserQuerySimulation这里选择0回车就行了,在下一步输入一个描述信息,可以不输直接回车也可以的,不影响,
接下来就是等了,效果如下:

PS D:\apps\gatling-charts-highcharts-bundle-3.5.1\bin> .\gatling.bat
GATLING_HOME is set to "D:\apps\gatling-charts-highcharts-bundle-3.5.1"
JAVA = ""C:\Program Files\Java\jdk1.8.0_281\bin\java.exe""
Choose a simulation number:
     [0] com.bzlrobot.test.tools.gatling.UserQuerySimulation
     [1] computerdatabase.BasicSimulation
     [2] computerdatabase.advanced.AdvancedSimulationStep01
     [3] computerdatabase.advanced.AdvancedSimulationStep02
     [4] computerdatabase.advanced.AdvancedSimulationStep03
     [5] computerdatabase.advanced.AdvancedSimulationStep04
     [6] computerdatabase.advanced.AdvancedSimulationStep05
0
Select run description (optional)
test
Simulation com.bzlrobot.test.tools.gatling.UserQuerySimulation started...

================================================================================
2021-05-15 15:03:45                                           5s elapsed
---- Requests ------------------------------------------------------------------
> Global                                                   (OK=400    KO=0     )
> 开始查询用户                                                   (OK=400    KO=0     )

---- 查询所有用户 --------------------------------------------------------------------
          active: 100    / done: 300
================================================================================

结果

跑完会有一个概览结果,还有一个详细的html的可视化结果

  • 概览结果:
imulation com.bzlrobot.test.tools.gatling.UserQuerySimulation completed in 60 seconds
Parsing log file(s)...
Parsing log file(s) done
Generating reports...

================================================================================
---- Global Information --------------------------------------------------------
> request count                                       5900 (OK=5900   KO=0     )
> min response time                                      2 (OK=2      KO=-     )
> max response time                                   1165 (OK=1165   KO=-     )
> mean response time                                    20 (OK=20     KO=-     )
> std deviation                                         92 (OK=92     KO=-     )
> response time 50th percentile                          6 (OK=6      KO=-     )
> response time 75th percentile                         10 (OK=10     KO=-     )
> response time 95th percentile                         26 (OK=26     KO=-     )
> response time 99th percentile                        565 (OK=565    KO=-     )
> mean requests/sec                                 96.721 (OK=96.721 KO=-     )
---- Response Time Distribution ------------------------------------------------
> t < 800 ms                                          5864 ( 99%)
> 800 ms < t < 1200 ms                                  36 (  1%)
> t > 1200 ms                                            0 (  0%)
> failed                                                 0 (  0%)
================================================================================

Reports generated in 0s.
Please open the following file: D:\apps\gatling-charts-highcharts-bundle-3.5.1\results\userquerysimulation-20210515070338757\index.html
  • 可根据上面的提示打开html报告:
    image.png