java编写一个简单的压力测试程序
程序员文章站
2022-07-14 23:17:54
...
一个简单的压力测试程序,可设置请求地址,并发请求的线程数和总请求数
代码结构如下:
下面直接贴代码
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打包配置
上一篇: 输出二进制表示
推荐阅读
-
简单的程序代码大全(教你编写一个简单的代码)
-
简单的程序代码大全(教你编写一个简单的代码)
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
java基础------环境变量的配置及编写第一个程序
-
Java入门(一)——编写一个简单的Java程序
-
什么是递归?用Java写一个简单的递归程序
-
基于Python编写一个计算器程序,实现简单的加减乘除和取余二元运算
-
Java经典编程习题100例:第18例:编写程序,将一个数组中的元素倒排过来。例如原数组为1,2,3,4,5;则倒排后数组中的值
-
C++ 实验二 NO.1_(3) 1:熟悉DEV环境,练习自己的第一个程序使用DEV集成环境来编辑,运行简单的数据输入和运算实验。(3)编写一个程序,要求:提示输入3个数;显示这3个数,求他们的平均值
-
java学习之路-练习题:编写一个计算速度的程序,距离时间常量。