压力测试工具详解

Apache Bench(AB)

小巧简单

localhost:config-cache biguodong$ ab --help
ab: wrong number of arguments
Usage: ab [options] [http[s]://]hostname[:port]/path
Options are:
    -n requests     请求总数
    -c concurrency  请求并发数
    -t timelimit    Seconds to max. to spend on benchmarking
                    This implies -n 50000
    -s timeout      Seconds to max. wait for each response
                    Default is 30 seconds
    -b windowsize   Size of TCP send/receive buffer, in bytes
    -B address      Address to bind to when making outgoing connections
    -p postfile     File containing data to POST. Remember also to set -T
    -u putfile      File containing data to PUT. Remember also to set -T
    -T content-type Content-type header to use for POST/PUT data, eg.
                    'application/x-www-form-urlencoded'
                    Default is 'text/plain'
    -v verbosity    How much troubleshooting info to print
    -w              Print out results in HTML tables
    -i              Use HEAD instead of GET
    -x attributes   String to insert as table attributes
    -y attributes   String to insert as tr attributes
    -z attributes   String to insert as td or th attributes
    -C attribute    Add cookie, eg. 'Apache=1234'. (repeatable)
    -H attribute    Add Arbitrary header line, eg. 'Accept-Encoding: gzip'
                    Inserted after all normal header lines. (repeatable)
    -g filename     Output collected data to gnuplot format file.
    -e filename     Output CSV file with percentages served

举个例子

ab -n 1000 -c 10 http://127/0.0.1:8080/test

返回结果

localhost:config-cache biguodong$ ab -n 1000 -c 10 http://127.0.0.1:8080/test
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
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:            8080

Document Path:          /test
Document Length:        4 bytes

Concurrency Level:      10//并发量
Time taken for tests:   6.699 seconds//整个测试使用时间
Complete requests:      1000//完成的请求数目
Failed requests:        0//失败的请求书
Total transferred:      136000 bytes//标示所有请求的响应数据长度总和,包括每个http响应数据的头信息和正文数据的信息,不包括http请求数据的长度,仅包括服务器流向用户pc的数据总长度;
HTML transferred:       4000 bytes//所有请求响应数据中正文数据的总和(除去头信息)
Requests per second:    149.29 [#/sec] (mean)//吞吐率,是与并发数有关的,是用Complete requests比上Time taken for tests即 1000/6.699
Time per request:       66.985 [ms] (mean)//用户平均等待时间
Time per request:       6.699 [ms] (mean, across all concurrent requests)//服务器平均等待时间
Transfer rate:          19.83 [Kbytes/sec] received//单位时间内从服务器获取到的数据长度Total transferred比上Time taken for tests即13600/6.699

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   1.0      0       8
Processing:     1   66 590.1      5    6059
Waiting:        0   35 417.3      4    5932
Total:          1   67 590.0      6    6059

Jmeter压力测试

几个参数

线程组的几个概念:

  1. 线程数:即虚拟用户数,有多少个虚拟用户并发模拟,如果模拟100个用户,输入100就好了;
  2. Ramp-Up Period(in seconds)虚拟用户增长时长:比如模拟一段时间的登录时间段,比如20分钟,但是,一般测试肯定不会这么长,我们估计出登录频率最高的时间段,如果我们设置为300,意思是100个用户在5min中内登录完毕;
  3. 循环次数:单个虚拟用户执行的次数;

步骤

  1. 先添加一个http请求


    添加一个Http请求

效果如下:


效果图
  1. 如果我们的请求需要添加header信息


    添加Header

效果如下:


效果图
  1. 添加断言查看结果
    响应断言,用来判断你的请求响应是否达到预期


    响应断言

效果如下:


效果图

配置查看结果树


查看结果树

配置聚合报告,做统计信息处理;


聚合报告

响应断言配合查看结果树


响应断言配合查看结果树

可以查看每个请求的请求request 和 response
响应断言配合聚合报告


响应断言配合聚合报告

结果集中统计了所有测试的响应时间、错误率等聚合信息;
在配置一个图形结果


图形结果

效果如下:


效果图

这里的各项数据含义自己要好好弄清楚奥,这里不赘述了
其他元件的使用自己去安装一个jmeter压力测试起来吧~~

代码来做压力测试

CountDownLatch

(字面的意思是计数器往下减的一个闭锁)的使用

概念图
  1. 假设计数器的值为 3
  2. 线程 A 调用了 await() 方法后,当前线程 A 进入awaiting状态;
  3. 在其他进程的代码里,每次执行countDown()这个方法后,计数器的值就会减 1;
  4. 当计数器从 3 主键变成 0 之后,线程A就继续执行;

CountDownLatch可以阻塞线程,并在达到一定条件后继续执行;

适合线程打到一定的条件后继续其他的操作;

Semphore

概念图

字面意思:信号量,类比交通工具-红绿灯
可以阻塞进行,并且可以控制同一时间的并发量;

适合控制线程的并发数;

代码拿来:
这里自定义了线程池,以及自定义拒绝策略实现,这里为了测试在 add() 方法中添加了 sleep()等待

@Slf4j
@NotThreadSafe
public class CountExample1 {
    /**
     * 执行总数,5000次加一操作
     */
    private static final int REQUEST_TOTAL = 5000;
    /**
     * 同一时间的并发总数
     */
    private static final int CONCURRENCY_COUNT = 20;
    private static final int MAXIMUM_POOL_SIZE = 100;
    private static int count = 0;

    public static void main(String[] args) throws Exception{
        // 所有请求执行完毕之后统计我们的执行结果,因此这里使用的是 REQUEST_TOTAL
        final CountDownLatch countDownLatch = new CountDownLatch(REQUEST_TOTAL);
        final Semaphore semaphore = new Semaphore(CONCURRENCY_COUNT);
        // 初始化一个线程池
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("con-%s").build();
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(CONCURRENCY_COUNT, MAXIMUM_POOL_SIZE, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(30), threadFactory, new BlockingPolicy());

        for(int i = 0; i < REQUEST_TOTAL; i ++) {
            threadPoolExecutor.execute(() -> {
                try{
                    // 每个线程执行前需要尝试获取信号量(是否允许被执行,如果达到并发数,当前线程会被阻塞)
                    semaphore.acquire();
                    add();
                    // 执行完毕之后释放信号量
                    semaphore.release();
                }catch (Exception e){
                    log.error("caught some error", e);
                }
                // 线程执行完毕后执行次数 - 1
                countDownLatch.countDown();
                //countDownLatch.countDown();
            });
        }
        // 所有线程执行完毕之后,输出我们的结果
        countDownLatch.await();
        // 线程池执行完毕之后关闭线程池
        threadPoolExecutor.shutdown();
        log.info(">>>>>>>>>>>> : count:{}", count);
    }

    private static void add() throws InterruptedException{
        TimeUnit.MILLISECONDS.sleep(100);
        count ++;
    }
}

上述测试了线程的队列、线程池的拒接策略等问题,实际中可将QueueSize 调整大于 5000,自定义拒绝策略中,把任务又重新放回了队列中;
不断调整Sleep()时间大小,越大,返回的count越小,因为每个线程执行的时间加长,导致协会主存的count是同一个数的概率增大!

16:41:59.647 [main] INFO com.mmall.concurrency.example.count.bigd.CountExample1 - >>>>>>>>>>>> : count:4859

快使用起来吧~~

你可能感兴趣的:(压力测试工具详解)