在应用程序上线以前,有多少人作过性能测试?git
估计大部分开发者更多地关注功能测试,而且会提供一些单元测试和集成测试的用例。然而,有时候性能漏洞致使的影响比未发现的业务漏洞更严重,由于性能漏洞影响的是整个系统,而不单单是一个业务进程。github
可能大家不少人听过 JMeter ,可是今天将介绍有竞争力的解决方案 —— Gatling 。它能生成丰富多彩的报告,包含测试案例中收集的全部指标。该功能彷佛比 JMeter 更好。docker
在讨论 Gatling 以前,先了解下理论知识,性能测试的两种类型,负载测试和压力测试:数据库
Gatling 是一个功能强大的负载测试工具。它是为易用性、可维护性和高性能而设计的。apache
开箱即用,Gatling 带有对 HTTP 协议的出色支持,使其成为负载测试任何 HTTP 服务器的首选工具。因为核心引擎其实是协议不可知的,因此彻底能够实现对其余协议的支持,例如,Gatling 目前也提供JMS 支持。json
只要底层协议(如 HTTP)可以以非阻塞的方式实现,Gatling 的架构就是异步的。这种架构能够将虚拟用户做为消息而不是专用线程来实现。所以,运行数千个并发的虚拟用户不是问题。服务器
建立 Spring Boot 应用,提供 RESTful API,以供测试微信
https://github.com/ChinaSilence/gatling-test.git网络
若是有本身测试的 Web 应用能够忽略本步骤!架构
启动数据库
Github 中的示例代码依赖了 PostgresSQL,因此要先启动数据库,最简单的方式固然是用 Docker 咯:
docker run -d \ --name postgres \ -e POSTGRES_DB=gatling \ -e POSTGRES_USER=gatling \ -e POSTGRES_PASSWORD=gatling123 \ -p 5432:5432 \ postgres
在 IDEA 中安装 scala 环境
安装 scala 插件
安装 scala SDK
编写性能测试脚本
每个 Gatling 测试都要继承 Simulation
类,在里面你可使用Gatling Scala DSL 来声明一个场景列表。这里的目标是运行 30 个客户端,同时发送 1000 次请求。首先,客户端经过调用 POST /persons
方法将添加数据到数据库中;而后,尝试经过调用 GET /persons/{id}
方法使用 id 来查询数据。
class ApiGatlingSimulationTest extends Simulation { val scn = scenario("AddAndFindPersons").repeat(1000, "n") { exec( http("AddPerson-API") .post("http://localhost:8080/persons") .header("Content-Type", "application/json") .body(StringBody("""{"firstName":"John${n}","lastName":"Smith${n}","birthDate":"1980-01-01", "address": {"country":"pl","city":"Warsaw","street":"Test${n}","postalCode":"02-200","houseNo":${n}}}""")) .check(status.is(200)) ).pause(Duration.apply(5, TimeUnit.MILLISECONDS)) }.repeat(1000, "n") { exec( http("GetPerson-API") .get("http://localhost:8080/persons/${n}") .check(status.is(200)) ) } setUp(scn.inject(atOnceUsers(30))).maxDuration(FiniteDuration.apply(10, "minutes")) }
运行 Spring Boot 应用
运行测试脚本
配置 Maven 插件参数
<build> <plugins> <plugin> <groupId>io.gatling</groupId> <artifactId>gatling-maven-plugin</artifactId> <version>${gatling-plugin.version}</version> <configuration> <!-- 测试脚本 --> <simulationClass>com.anoyi.test.ApiGatlingSimulationTest</simulationClass> <!-- 结果输出地址 --> <resultsFolder>/Users/admin/code/gatling</resultsFolder> </configuration> </plugin> </plugins> </build>
执行测试
mvn gatling:execute
查看测试报告
全局报告
单个接口明细报告
连接:https://www.jianshu.com/p/cdd9d29256c0
如但愿了解更多,请关注微信公众号