欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java编写一个简单的压力测试程序

程序员文章站 2022-07-14 23:17:54
...

一个简单的压力测试程序,可设置请求地址,并发请求的线程数和总请求数

代码结构如下:

java编写一个简单的压力测试程序
下面直接贴代码

1.pom依赖

<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.25</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.7</version>
		</dependency>
	</dependencies>

2.RequestThread.java源码

public class RequestThread implements Runnable {
	private static final Logger LOG = LoggerFactory.getLogger(RequestThread.class);
	private CountDownLatch countDownLatch;
	private String requestUrl;

	public RequestThread(String requestUrl, CountDownLatch countDownLatch) {
		this.requestUrl = requestUrl;
		this.countDownLatch = countDownLatch;
	}

	public void run() {
		try {
			boolean isSuccess = HttpClientUtil.get(requestUrl, null);
			if (!isSuccess) {
				LOG.error("response error.....threadName:" + Thread.currentThread().getName());
			}
			countDownLatch.countDown();
		} catch (Exception e) {
			LOG.error("requset error.....threadName:" + Thread.currentThread().getName());
		}

	}

}

3.StressTest.java源码

public class StressTest {
	private static Integer threadCount = 0;
	private static String requestUrl = null;
	private static Integer requestCount = 0;
	private static ExecutorService ThreadPool = null;
	static {
		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		System.out.println("start execute.....");
		long startTime = System.currentTimeMillis();
		exec();
		long endTime = System.currentTimeMillis();
		System.out.println("execute end ....spendTime:" + (endTime - startTime));

	}

	private static void init() throws IOException {
		Properties properties = PropertiesUtil.getProperties("config.peoperties");
		threadCount = Integer.valueOf(properties.getProperty("thread_count"));
		requestCount = Integer.valueOf(properties.getProperty("request_count"));
		requestUrl = properties.getProperty("request_url");
		ThreadPool = Executors.newFixedThreadPool(threadCount);
	}

	private static void exec() throws InterruptedException {

		CountDownLatch requestCountDown = new CountDownLatch(requestCount);
		for (int i = 0; i < requestCount; i++) {
			RequestThread requestThread = new RequestThread(requestUrl, requestCountDown);
			ThreadPool.execute(requestThread);
		}
		requestCountDown.await();
	}

}

4.HttpClientUtil.java源码

public class HttpClientUtil {

	private static CloseableHttpClient httpClient = HttpClients.createDefault();
	private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);

	public static boolean get(String url, Map<String, String> param) {
		// String result = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				// result = EntityUtils.toString(response.getEntity(), "utf-8");
				return true;
			} else {
				LOG.error("Request is unsuccess,responseCode:" + response.getStatusLine().getStatusCode()
						+ " ,responseMsg:" + EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			LOG.error("Request error,exceptionInfo:" + ExceptionUtils.getStackTrace(e));
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}

	public static String post(String url, Map<String, String> param) {
		String result = "";
		CloseableHttpResponse response = null;
		try {

			HttpPost post = new HttpPost(url);
			requestSetEntity(post, param);
			response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
			} else {
				LOG.error("Request is unsuccess,responseCode:" + response.getStatusLine().getStatusCode()
						+ " ,responseMsg:" + EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			LOG.error("Request error,exceptionInfo:" + ExceptionUtils.getStackTrace(e));
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static String post(String url, String param) {
		String result = "";
		CloseableHttpResponse response = null;
		try {

			HttpPost post = new HttpPost(url);
			requestSetEntity(post, param);
			response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
			} else {
				LOG.error("Request is unsuccess,responseCode:" + response.getStatusLine().getStatusCode()
						+ " ,responseMsg:" + EntityUtils.toString(response.getEntity(), "utf-8"));
			}
		} catch (Exception e) {
			LOG.error("Request error,exceptionInfo:" + ExceptionUtils.getStackTrace(e));
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	private static void requestSetEntity(HttpEntityEnclosingRequestBase request, Map<String, String> data) {
		if (data != null && !data.isEmpty()) {
			List<NameValuePair> list = new ArrayList<>();
			for (String key : data.keySet()) {
				list.add(new BasicNameValuePair(key, data.get(key)));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity encodedFormEntity;
				try {
					encodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
					request.setEntity(encodedFormEntity);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					throw new RuntimeException();
				}

			}
		}
	}

	private static void requestSetEntity(HttpEntityEnclosingRequestBase request, String param) {
		if (StringUtils.isNotEmpty(param)) {
			request.setEntity(new StringEntity(param, "utf-8"));
		}
	}
}

5.PropertiesUtil.java源码

public static Properties getProperties(String path) throws IOException {
		InputStream inputStream = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("config.properties");
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}

6.config.properties配置

thread_count=2 #请求线程数
request_count=50 #请求总数
request_url=http://localhost:8080/stress #请求地址

运行StressTest.java类就可以了
部署到服务器上还需要打包,
可参加maven打包配置