本代码用于测试Tomcat服务器压力
要求在原有的基础上做出如下改进:
1、当连接返回的时间超过5S则认为连接失败,结束测试,返回失败结果。
2、如果可以的话最好编写一个简单的图形化界面,用于输入线程数,显示返回结果等。
[code="java"]package com.eteda.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TomcatTest {
private static String url = "http://10.226.144.175:8080/index.jsp";
private static Integer error = 0;
private static Integer threads = 200;
private static Long startTime;
private static Long totleTime;
public static void main(String[] args) {
WorkThread[] workThreads = new WorkThread[threads];
for (int i = 0; i < threads; i++) {
workThreads[i] = new WorkThread();
}
startTime = System.currentTimeMillis();
//System.out.printf("线程数组初始化耗时%d毫秒\n", (System.currentTimeMillis() -startTime));
for (int i = 0; i < threads; i++) {
workThreads[i].start();
}
// if(error >= 1){
// System.out.println("本次测试结束!压力超标,请调小线程数量再测试一次!");
// }else{
// System.out.println("本次测试结束!未达上限,请调大线程数量再测试一次!");
// }
}
private static class WorkThread extends Thread {
public void run() {
@SuppressWarnings("unused")
long start = System.currentTimeMillis();
long end = 0;
try {
URL u = new URL(url);
HttpURLConnection urlConn = (HttpURLConnection) u
.openConnection();
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-type",
"text/html; charset=UTF-8");
urlConn.connect();
InputStream is = urlConn.getInputStream();
StringBuffer buffer = new StringBuffer();
readToBuffer(buffer, is);
end = System.currentTimeMillis();
totleTime = end - startTime;
} catch (Exception e) {
synchronized (error) {
error++;
}
e.printStackTrace();
}
synchronized (threads) {
threads--;
// System.out.printf("还有%d个未完线程, 耗时%d毫秒\n", threads,
// (System.currentTimeMillis() - startTime));
if (threads == 0) {
System.out.printf("总耗时:%d毫秒\n",totleTime);
System.out.printf("连接失败数量:%d\n", error);
}
}
}
public void readToBuffer(StringBuffer buffer, InputStream is)
throws IOException {
String line; // 用来保存每行读取的内容
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\n"); // 添加换行符
line = reader.readLine(); // 读取下一行
}
}
}
}[/code]