使用多线程模拟多用户并发访问一个或多个tomcat,测试性能 java
2015-10-06 16:22
961 查看
Java代码
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();
}
}
}
Java代码
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");
}
}
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();
}
}
}
Java代码
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");
}
}
相关文章推荐
- Linux下Tomcat的启动、关闭、杀死进程
- HTML5 WebSocket+Tomcat实现Web版即时聊天室
- 常见服务器Apache/Tomcat/JBOSS/Jetty/Nginx区别与对比
- 一秒解决直接双击启动tomcat-startup.bat闪退
- linux 下tomcat开机自启动
- Tomcat最大连接数问题修改
- tomcat下jndi的全局配置方式
- 仿Tomcat应用隔离机制开发Openfire插件隔离功能笔记
- 在ubuntu下 eclipse中配置tomcat
- 阿里云CentOS下yum安装mysql,jdk以及tomcat
- 登陆tomcat首页报404的问题
- Target runtime Apache Tomcat v6.0 is not defined
- tomcat6配置
- Maven 安装Tomcat插件与Jeety插件
- JBoss和Tomcat是什么?有什么用?如何部署?----从底层看web应用(1)
- Eclipse Tomcat改发布目录
- J2EE中关于tomcat的maxIdle、maxActive、maxActive相关配置
- tomcat的配置与安装
- tomcat的配置
- 上传图片问题