温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Gateling进行性能测试

发布时间:2021-09-17 11:28:56 阅读:239 作者:chen 栏目:编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章主要讲解了“如何使用Gateling进行性能测试”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何使用Gateling进行性能测试”吧!

Gatling是什么?

Gatling 是一个用 Scala 编写的负载测试工具,功能强大。它完全支持 HTTP 协议,也可以用来测试 JDBC 连接和 JMS。使用 Gatling 时,需要用 Scala dsl 代码定义测试场景。值得一提的是,Gatling 生成的 HTML 负载报告内容全面,并且提供了 Gradle、Maven 和 Jenkins 插件方便集成。

构建示例应用

开始测试前,需要准备测试应用。示例程序非常简单,源代码可以在 GitHub 上找到(github.com/piomin/sample-gatling-load-tests)。它提供了一组 CRUD 操作的 RESTful HTTP API,在可以数据库中新增和搜索 Entity。数据库用 Postgres,基于 Spring Boot 构建,使用Spring Data 实现持久层。

plugins {    id 
'org.springframework.boot' version 
'1.5.9.RELEASE'}dependencies {compile group: 
'org.springframework.boot', name: 
'spring-boot-starter-web'compile group: 
'org.springframework.boot', name: 
'spring-boot-starter-data-jpa'compile group: 
'org.postgresql', name: 
'postgresql', version: 
'42.1.4'testCompile group: 
'org.springframework.boot', name: 
'spring-boot-starter-test'}

Person entity映射到 person 表。

@Entity@SequenceGenerator(name = 
"seq_person", initialValue = 
1, allocationSize = 
1)public class Person {@Id@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = 
"seq_person")private Long id;@Column(name = 
"first_name")private String firstName;@Column(name = 
"last_name")private String lastName;@Column(name = 
"birth_date")private Date birthDate;@Embeddedprivate Address address;// ...}

数据库连接设置和 Hibernate 属性配置在 application.yml 中。

spring:  application:    name: gatling-service  datasource:    url: jdbc:postgresql://192.168.99.100:5432/gatling    username: gatling    password: gatling123  jpa:    properties:      hibernate:        hbm2ddl:          auto: updateserver:  port: 
8090

正如之前提到的,示例程序提供了在数据库中添加、搜索 person 的 API,下面是 Spring REST controller 实现。

@RestController@RequestMapping("/persons")public class PersonsController {private static final Logger LOGGER = LoggerFactory.getLogger(PersonsController.class);@AutowiredPersonsRepository repository;@GetMapping function(){   //外汇跟单www.gendan5.compublic List<Person> findAll() {  return (List  <Person>) repository.findAll();    }    @PostMapping    public Person 
add(@RequestBody Person person) {    Person p = repository.save(person);    LOGGER.info("add: {}", p.toString());    return p;    }    @GetMapping("/{id}")    public Person 
findById(@PathVariable("id") Long id) {    LOGGER.info("findById: id={}", id);    return repository.findOne(id);    }    }

运行数据库

开发示例程序的下一步是运行数据库,最合适的方式是 Docker image。下面的 Docker 命令会启动一个 Postgres container,完成 gatling 用户和数据库初始化。

docker run -d --name postgres -e POSTGRES_DB=gatling -e POSTGRES_USER=gatling -e POSTGRES_PASSWORD=gatling123 -p 5432:5432 postgres

设计测试场景

每个 Gatling test suite 都要继承 Simulation 类,使用 Gatling Scala DSL 声明一系列测试场景。我们的目标是启动30个客户端,同时发送1000次请求。首先,客户端通过 POST /persons 方法向数据库添加 person。然后,调用 GET /persons/{id}搜索 person。总共向应用程序发送6万次请求:3万次 POST,3万次 GET。下面代码展示了测试场景,非常简单。在 src/test/scala 目录下可以找到 ApiGatlingSimulationTest。

class ApiGatlingSimulationTest extends Simulation {  val scn = scenario("AddAndFindPersons").repeat(1000, 
"n") {        exec(          http("AddPerson-API")            .post("http://localhost:8090/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:8090/persons/${n}")            .check(status.is(200))        )  }  setUp(scn.inject(atOnceUsers(30))).maxDuration(FiniteDuration.apply(10, 
"minutes"))}

为了在项目中启用 Gatling 框架,还需要在 Gradle 构建文件中添加依赖。

testCompile group'io.gatling.highcharts', name: 'gatling-charts-highcharts', version: '2.3.0'

运行测试

通过一些 Gradle 插件可以在项目构建期间运行测试。但是,也可用 io.gatling.app.Gatling 类定义简单的 gradle 任务。

task 
loadTest(type: JavaExec) {   dependsOn testClasses   description = 
"Load Test With Gatling"   group = 
"Load Test"   classpath = sourceSets.test.runtimeClasspath   jvmArgs = [        "-Dgatling.core.directory.binaries=${sourceSets.test.output.classesDir.toString()}"   ]   main = 
"io.gatling.app.Gatling"   args = [           
"--simulation", 
"pl.piomin.services.gatling.ApiGatlingSimulationTest",           
"--results-folder", 
"${buildDir}/gatling-results",           
"--binaries-folder", sourceSets.test.output.classesDir.toString(),           
"--bodies-folder", sourceSets.test.resources.srcDirs.toList().first().toString() + 
"/gatling/bodies",   ]}

使用 gradle loadTest 执行定义好的 Gradle 任务。当然,运行测试之前需要启动应用程序,在 IDE 中启动 main class pl.piomin.services.gatling.ApiApplication 或者执行 java -jar build/libs/sample-load-test-gatling.jar 命令。

测试报告

测试执行完毕会以文本形式打印报告。

================================================================================---- Global Information --------------------------------------------------------> request count                                      60000 (OK=60000  KO=0     )> min response time                                      2 (OK=2      KO=-     )> max response time                                   
1338 (OK=1338   KO=-     )> mean response time                                    80 (OK=80     KO=-     )> 
std deviation                                        106 (OK=106    KO=-     )> response time 
50th percentile                         
50 (OK=50     KO=-     )> response time 
75th percentile                         
93 (OK=93     KO=-     )> response time 
95th percentile                        253 (OK=253    KO=-     )> response time 
99th percentile                        564 (OK=564    KO=-     )> mean requests/sec                                319.149 (OK=319.149 KO=-     )---- Response Time Distribution ------------------------------------------------> t < 
800 ms                                         
59818 (100%) > 
800 ms < t < 
1200 ms                                 
166 (  0%) > t > 
1200 ms                                           
16 (  0%)> failed                                                 
0 (  0%)================================================================================

但是,Gatling 最擅长的是报告图表。生成的 HTML 报告在 build/gatling-results 目录下。第一个报告展示了全局信息,包含请求总数和最大响应时间(百分比)。例如,95%的 GetPerson API 请求的最大响应时间为206ms。

感谢各位的阅读,以上就是“如何使用Gateling进行性能测试”的内容了,经过本文的学习后,相信大家对如何使用Gateling进行性能测试这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:http://blog.itpub.net/69946337/viewspace-2661909/

AI

开发者交流群×