httpclient 接口测试多线程并发类封装(新)

之前写过一个httpclient多线程并发类的代码,今天分享的新版主要增加了对多个不同的请求进行并发测试的功能,具体获取请求对象的方法在其他文章分享过了这里就不再贴代码了(包括cookies和header设置以及并发类的使用)。分享代码供大家参考。

package com.fission.source.source;

import org.apache.http.client.methods.HttpRequestBase;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Concurrent extends ApiLibrary {
	public HttpRequestBase request;
	public int threads;
	public int times;
	public List<HttpRequestBase> requests;

	/**
	 * 多请求单线程多次请求方法
	 *
	 * @param requests 请求列表
	 * @param times    单个请求的请求次数
	 */
	public Concurrent(List<HttpRequestBase> requests, int times) {
		this.requests = requests;
		this.times = times;
		this.threads = requests.size();
	}

	/**
	 * 单请求多线程多次任务构造方法
	 *
	 * @param request 被执行的请求
	 * @param threads 线程数
	 * @param times   每个线程运行的次数
	 */
	public Concurrent(HttpRequestBase request, int threads, int times) {
		this.request = request;
		this.threads = threads;
		this.times = times;
	}

	/**
	 * 执行多线程任务
	 */
	public void excuteTreads() {
		ExecutorService executorService = Executors.newFixedThreadPool(threads);
		CountDownLatch countDownLatch = new CountDownLatch(threads);
		Date start = new Date();
		for (int i = 0; i < threads; i++) {
			executorService.execute(new More(countDownLatch, getRequest(i)));
		}
		try {
			countDownLatch.await();
			executorService.shutdown();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Date end = new Date();
		output("总计" + threads + "个线程,总计" + (threads * times) + "次请求,共用时:" + getTimeDiffer(start, end) + "秒!");
		saveRequestTimes();
	}

	/**
	 * 保存请求时间到本地文件
	 */
	public static void saveRequestTimes() {
		StringBuffer buffer = new StringBuffer();
		int length = testTimes.size();
		for (int i = 0; i < length; i++) {
			if (i == 0) {
				buffer.append(testTimes.get(0));
				continue;
			}
			buffer.append(LINE + testTimes.get(i));
		}
		logLong(buffer.toString());
	}

	/**
	 * 获取请求
	 *
	 * @param i 个
	 * @return
	 */
	private HttpRequestBase getRequest(int i) {
		if (requests == null)
			return request;
		return requests.get(i);
	}

	/**
	 * 多线程类
	 */
	class More implements Runnable {
		private CountDownLatch countDownLatch;
		private HttpRequestBase request;

		public More(CountDownLatch countDownLatch, HttpRequestBase request) {
			this.countDownLatch = countDownLatch;
			this.request = request;
		}

		@Override
		public void run() {
			try {
				executeRequest(request, times);
			} finally {
				countDownLatch.countDown();
			}
		}

	}
}

分享一下QQ群:群号:340964272


阅读更多
想对作者说点什么? 我来说一句

springmvc 接口测试必备

2018年05月14日 78.59MB 下载

没有更多推荐了,返回首页

不良信息举报

httpclient 接口测试多线程并发类封装(新)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭