实际开发中,我们经常需要对项目进行压力测试,而ApacheBench作为Apache自带的一个压力测试工具,可以很好的帮助我们了解网站这方面的性能。

简介

ApacheBench简称ab,是Apache自带的一个压力测试工具,可以对网站进行访问压力测试,非常简单实用。ab是一个命令行工具,它可以模仿多个用户对网站的多并发访问,来测试目标服务器的负载能力。通过输出一些关键指标参数,帮助我们了解、提升服务器的负载能力。

安装

  • Linux环境
    在linux环境下的安装yum install httpd-tools
  • MacOS环境

    • 下载Apache Http Server;
    • 安装如下 brew install apr brew install pcre;
    • 进入到httpd目录下,执行

      1
      2
      3
      ./configure
      make
      make install

使用

可以通过ab -h来查看ab的参数情况。
这里我们模仿50个用户同时访问一个本地服务,访问100次,执行以下命令

1
ab -c 50 -n 100 http://127.0.0.1:5500/10-color/cubehelix/index.html

输出如下结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
This is ApacheBench, Version 2.3 <$Revision: 1843412 $>
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).....done


Server Software: #服务器软件
Server Hostname: 127.0.0.1 #服务器IP
Server Port: 5500 # 服务器端口

Document Path: /10-color/cubehelix/index.html #文件路径
Document Length: 1910 bytes # 字面字节数

Concurrency Level: 50 #请求的并发数
Time taken for tests: 0.233 seconds #访问的总耗时
Complete requests: 100 #请求成功数
Failed requests: 0 #请求失败数
Total transferred: 223000 bytes #请求的总数据大小(包含header头信息)
HTML transferred: 191000 bytes #页面实际总字节数
Requests per second: 429.41 [#/sec] (mean) #每秒请求数,反应了服务器的吞吐量,非常重要
Time per request: 116.439 [ms] (mean) #用户平均请求等待时间
Time per request: 2.329 [ms] (mean, across all concurrent requests) #服务器平均处理时间,也就是服务器吞吐量的倒数
Transfer rate: 935.14 [Kbytes/sec] received #每秒获取数据长度

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 1 0.5 1 2
Processing: 38 84 37.0 120 123
Waiting: 34 78 36.4 108 122
Total: 40 86 37.0 122 123

Percentage of the requests served within a certain time (ms)
50% 122 #50%用户请求在122ms内返回
66% 122 #66%用户请求在122ms内返回
75% 122 #75%用户请求在122ms内返回
80% 122 #80%用户请求在122ms内返回
90% 123 #90%用户请求在123ms内返回
95% 123 #95%用户请求在123ms内返回
98% 123 #98%用户请求在123ms内返回
99% 123 #99%用户请求在123ms内返回
100% 123 (longest request)

补充

ab作为一种压力测试工具,可以帮助我们提升服务器的负载能力。在实际应用中,为了提升服务器的稳定性,我们还可以有更多的方法,例如对同一用户的多次请求进行降频,在我们用ab工具对百度搜索进行测试时,就发现这个现象。