您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何使用Gateling進(jìn)行性能測試”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“如何使用Gateling進(jìn)行性能測試”吧!
Gatling是什么?
Gatling 是一個(gè)用 Scala 編寫的負(fù)載測試工具,功能強(qiáng)大。它完全支持 HTTP 協(xié)議,也可以用來測試 JDBC 連接和 JMS。使用 Gatling 時(shí),需要用 Scala dsl 代碼定義測試場景。值得一提的是,Gatling 生成的 HTML 負(fù)載報(bào)告內(nèi)容全面,并且提供了 Gradle、Maven 和 Jenkins 插件方便集成。
構(gòu)建示例應(yīng)用
開始測試前,需要準(zhǔn)備測試應(yīng)用。示例程序非常簡單,源代碼可以在 GitHub 上找到(github.com/piomin/sample-gatling-load-tests)。它提供了一組 CRUD 操作的 RESTful HTTP API,在可以數(shù)據(jù)庫中新增和搜索 Entity。數(shù)據(jù)庫用 Postgres,基于 Spring Boot 構(gòu)建,使用Spring Data 實(shí)現(xiàn)持久層。
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;
@Embedded
private Address address;
// ...
}
數(shù)據(jù)庫連接設(shè)置和 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: update
server:
port:
8090
正如之前提到的,示例程序提供了在數(shù)據(jù)庫中添加、搜索 person 的 API,下面是 Spring REST controller 實(shí)現(xiàn)。
@RestController
@RequestMapping("/persons")
public class PersonsController {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonsController.class);
@Autowired
PersonsRepository repository;
@GetMapping function(){ //外匯跟單www.gendan5.com
public 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);
}
}
運(yùn)行數(shù)據(jù)庫
開發(fā)示例程序的下一步是運(yùn)行數(shù)據(jù)庫,最合適的方式是 Docker image。下面的 Docker 命令會(huì)啟動(dòng)一個(gè) Postgres container,完成 gatling 用戶和數(shù)據(jù)庫初始化。
docker run -d --name postgres -e POSTGRES_DB=gatling -e POSTGRES_USER=gatling -e POSTGRES_PASSWORD=gatling123 -p 5432:5432 postgres
設(shè)計(jì)測試場景
每個(gè) Gatling test suite 都要繼承 Simulation 類,使用 Gatling Scala DSL 聲明一系列測試場景。我們的目標(biāo)是啟動(dòng)30個(gè)客戶端,同時(shí)發(fā)送1000次請(qǐng)求。首先,客戶端通過 POST /persons 方法向數(shù)據(jù)庫添加 person。然后,調(diào)用 GET /persons/{id}搜索 person。總共向應(yīng)用程序發(fā)送6萬次請(qǐng)求: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"))
}
為了在項(xiàng)目中啟用 Gatling 框架,還需要在 Gradle 構(gòu)建文件中添加依賴。
testCompile group: 'io.gatling.highcharts', name: 'gatling-charts-highcharts', version: '2.3.0'
運(yùn)行測試
通過一些 Gradle 插件可以在項(xiàng)目構(gòu)建期間運(yùn)行測試。但是,也可用 io.gatling.app.Gatling 類定義簡單的 gradle 任務(wù)。
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 執(zhí)行定義好的 Gradle 任務(wù)。當(dāng)然,運(yùn)行測試之前需要啟動(dòng)應(yīng)用程序,在 IDE 中啟動(dòng) main class pl.piomin.services.gatling.ApiApplication 或者執(zhí)行 java -jar build/libs/sample-load-test-gatling.jar 命令。
測試報(bào)告
測試執(zhí)行完畢會(huì)以文本形式打印報(bào)告。
================================================================================
---- 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 最擅長的是報(bào)告圖表。生成的 HTML 報(bào)告在 build/gatling-results 目錄下。第一個(gè)報(bào)告展示了全局信息,包含請(qǐng)求總數(shù)和最大響應(yīng)時(shí)間(百分比)。例如,95%的 GetPerson API 請(qǐng)求的最大響應(yīng)時(shí)間為206ms。
感謝各位的閱讀,以上就是“如何使用Gateling進(jìn)行性能測試”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)如何使用Gateling進(jìn)行性能測試這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。