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打包配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章