使用多線程模擬多用戶併發訪問一個或多個tomcat,測試性能

package test;

import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

public class CallHttpRequest implements Runnable {
private static Logger log = Logger.getLogger(CallHttpRequest.class);
public static int successRequest = 0;
public static int failRequest = 0;
public static int timeOutRequest = 0;
private final String hostString = "http://localhost:";
private String port;
private String puductPartURL;

private CountDownLatch begin;
private CountDownLatch end;

CallHttpRequest(String port, String puductPartURL, CountDownLatch begin,
CountDownLatch end) {
this.port = port;
this.puductPartURL = puductPartURL;
this.begin = begin;
this.end = end;
}

private String makeFullURL() {
return hostString + port + puductPartURL;

}
private static synchronized void incrementSuccessCount(){
successRequest++;
}

private static synchronized void incrementFailCount(){
failRequest++;
}

private static synchronized void incrementTimeOutCount(){
timeOutRequest++;
}

@Override
public void run() {
String urlStr = makeFullURL();
URL url;
try {
begin.await();
url = new URL(urlStr);
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
httpConnection.setConnectTimeout(3000);
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
incrementSuccessCount();
} else {
incrementFailCount();
}
} catch (SocketTimeoutException e) {
incrementTimeOutCount();
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
end.countDown();
}

}

}



package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class ParseUrl {
private static Logger log = Logger.getLogger(ParseUrl.class);

private static final String[] portArray = new String[] { "1111", "2222",
"3333" };

/*從文件中使用正則解析出url的部分信息,下面正則是將 以/開頭的,非空白字符結尾的字符串取出,如“/abcc空格”字符串,\s爲任意的空白符 */
public static ArrayList<String> fetchUrlFromFile(String str) {
ArrayList<String> arrayList = new ArrayList<String>();
Pattern urlPattern = Pattern.compile("/[^\\s]+");
//Pattern urlPattern = Pattern.compile("/[\\S]+");
Matcher matcher = urlPattern.matcher(str);
while (matcher.find()) {
arrayList.add(matcher.group());
}
return arrayList;
}

public static void main(String[] args) throws Exception {
CountDownLatch begin = new CountDownLatch(1);

StringBuilder stringBuilder = new StringBuilder();
String filePath = args[0];
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
stringBuilder.append(br.readLine());
}
String stringAll = stringBuilder.toString();
ArrayList<String> arrayList = fetchUrlFromFile(stringAll);
int allRequestSize = arrayList.size();
log.info("all request size is " + allRequestSize);
//設置最大的併發數量爲60
ExecutorService exec = Executors.newFixedThreadPool(60);

CountDownLatch end = new CountDownLatch(allRequestSize);
// int i = 0;
for (String str : arrayList) {
exec.execute(new CallHttpRequest(portArray[0], str, begin, end));

/*如果想測試60個線程併發的訪問,發配到同一臺服務器上的兩個tomcat,就用下面註釋掉的代碼
* if (i % 2 == 0) {
exec.execute(new CallHttpRequest(portArray[0], str, begin, end));
} else if (i % 2 == 1) {
exec.execute(new CallHttpRequest(portArray[1], str, begin, end));
} */
// i++;
}
long startTime = System.currentTimeMillis();
//當60個線程,初始化完成後,解鎖,讓六十個線程在4個雙核的cpu服務器上一起競爭着跑,來模擬60個併發線程訪問tomcat
begin.countDown();

try {
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log.info("all url requests is done!");
log.info("the success size: " + CallHttpRequest.successRequest);
log.info("the fail size: " + CallHttpRequest.failRequest);
log.info("the timeout size: " + CallHttpRequest.timeOutRequest);
double successRate = (double)CallHttpRequest.successRequest / allRequestSize;
log.info("the success rate is: " + successRate*100+"%");
long endTime = System.currentTimeMillis();
long costTime = endTime - startTime;
log.info("the total time cost is: " + costTime + " ms");
log.info("every request time cost is: " + costTime / allRequestSize
+ " ms");
}
exec.shutdown();
log.info("main method end");

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