web效能測試:apache benchmark(ab)
阿新 • • 發佈:2019-01-31
開發完網站或者web介面後,一個比較負責任的工作就是測試一下介面效能,也叫做壓力測試。web介面效能直接反映了介面的併發處理能力,一個數值評估通常可以給系統性能給出一個比較好的反饋。
本文介紹比較常用的web效能測試工具ab(apache benchmark)。
安裝
ab命令來源於apache工具包,ubuntu可以通過下面的命令安裝:
sudo apt-get install apache2-utils
用法
ab -n 1000 -c 100 http://www.test.com/test/api
如上所示,-n表示測試請求數目,-c表示併發度。測試結果顯示如下:
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software:
Server Hostname: 127.0.0.1
Server Port: 4001
Document Path: /
Document Length: 0 bytes
// 以上是你打壓力的host, port等一部分的資訊
Concurrency Level: 100 # 併發度
Time taken for tests: 2.987 seconds # 總時間
Complete requests: 1000 # 完成請求數目
Failed requests: 0 # 失敗次數
Write errors: 0
Total transferred: 637272 bytes # 總共傳輸資料
HTML transferred: 0 bytes
Requests per second: 334.74 [#/sec] (mean) # QPS,每秒完成的請求數目,是系統最重要的指標
Time per request: 298.739 [ms] (mean) # 每組請求用時
Time per request: 2.987 [ms] (mean, across all concurrent requests) # 平均每個請求用時
Transfer rate: 208.32 [Kbytes/sec] received # 網路傳輸速率
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.6 0 3
Processing: 24 297 780.6 39 2648
Waiting: 23 295 780.5 36 2646
Total: 25 298 781.1 39 2650
# 以上這段資料標誌了一個請求從連線,傳送資料,接收資料這個三個大致的時間,最小以及平均值
# 以下是請求完成時間的分佈,可以看出80%的請求在41毫秒內完成
Percentage of the requests served within a certain time (ms)
50% 39
66% 40
75% 41
80% 41
90% 2624
95% 2647
98% 2650
99% 2650
100% 2650 (longest request)
ab命令選項引數
ab命令通常還有許多選項,列舉一些常用的:
-t timelimit 測試時間限制,單位秒
-s timeout 每個請求時間限制,單位秒
-v verbosity 日誌輸出級別,可以選擇1, 2等,除錯使用
-T content-type POST/PUT介面的content-type
-p postfile POST請求傳送的資料檔案
測試POST請求
POST請求經常用到,在這裡把用法寫下來。
以x-www-form-urlencoded形式傳送
ab -n 1000 -c 100 -p post.txt -T 'application/x-www-form-urlencoded' http://www.test.com/test/api
假定需要傳送的json資料為 {name : “hello,world”}。
post.txt檔案內容:
name=hello,world
注意,在網上找到這種用法,普遍都這麼用,但是經過實際測試,資料始終傳送不成功。
經過摸索,發現可以通過multipart/form-data形式傳送。
以multipart/form-data形式傳送
ab -n 1000 -c 100 -p post.txt -T 'multipart/form-data; boundary=--WebKitFormBoundaryE19zNvXGzXaLvS5C' http://www.test.com/test/api
post.txt檔案內容如下:
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="name"
hello,world
----WebKitFormBoundaryE19zNvXGzXaLvS5C
POST的檔案內容可以通過postman測試介面來檢視。
效能測試得到的最重要的指標就是QPS(Requests per second),反映了介面的併發承受能力,也就是系統的峰值效能。如果對介面的呼叫超過了這一限制,就要考慮提升硬體或者做一些優化了。