使用多线程模拟多用户并发访问一个或多个tomcat,测试性能 java

Java代码   收藏代码
  1. package test;  
  2.   
  3. import java.net.HttpURLConnection;  
  4. import java.net.SocketTimeoutException;  
  5. import java.net.URL;  
  6. import java.net.URLConnection;  
  7. import java.util.concurrent.CountDownLatch;  
  8.   
  9. import org.apache.log4j.Logger;  
  10.   
  11. public class CallHttpRequest implements Runnable {  
  12.     private static Logger log = Logger.getLogger(CallHttpRequest.class);  
  13.     public  static int successRequest = 0;  
  14.     public  static int failRequest = 0;  
  15.     public  static int timeOutRequest = 0;  
  16.     private final String hostString = "http://localhost:";  
  17.     private String port;  
  18.     private String puductPartURL;  
  19.   
  20.     private CountDownLatch begin;  
  21.     private CountDownLatch end;  
  22.   
  23.     CallHttpRequest(String port, String puductPartURL, CountDownLatch begin,  
  24.             CountDownLatch end) {  
  25.         this.port = port;  
  26.         this.puductPartURL = puductPartURL;  
  27.         this.begin = begin;  
  28.         this.end = end;  
  29.     }  
  30.   
  31.     private String makeFullURL() {  
  32.         return hostString + port + puductPartURL;  
  33.   
  34.     }  
  35.     private  static synchronized void incrementSuccessCount(){  
  36.          successRequest++;  
  37.     }  
  38.       
  39.     private  static synchronized void incrementFailCount(){  
  40.          failRequest++;  
  41.     }  
  42.       
  43.     private static synchronized void incrementTimeOutCount(){  
  44.          timeOutRequest++;  
  45.     }  
  46.       
  47.     @Override  
  48.     public void run() {  
  49.         String urlStr = makeFullURL();  
  50.         URL url;  
  51.         try {  
  52.             begin.await();  
  53.             url = new URL(urlStr);  
  54.             URLConnection URLconnection = url.openConnection();  
  55.             HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;  
  56.             httpConnection.setConnectTimeout(3000);  
  57.             int responseCode = httpConnection.getResponseCode();  
  58.             if (responseCode == HttpURLConnection.HTTP_OK) {  
  59.                 incrementSuccessCount();  
  60.             } else {  
  61.                 incrementFailCount();  
  62.             }  
  63.         } catch (SocketTimeoutException e) {  
  64.             incrementTimeOutCount();  
  65.             log.error(e.getMessage(), e);  
  66.         } catch (Exception e) {  
  67.             log.error(e.getMessage(), e);  
  68.         } finally {  
  69.             end.countDown();  
  70.         }  
  71.   
  72.     }  
  73.   
  74. }  


Java代码   收藏代码
  1. package test;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileReader;  
  5. import java.util.ArrayList;  
  6. import java.util.concurrent.CountDownLatch;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.regex.Matcher;  
  10. import java.util.regex.Pattern;  
  11.   
  12. import org.apache.log4j.Logger;  
  13.   
  14. public class ParseUrl {  
  15.     private static Logger log = Logger.getLogger(ParseUrl.class);  
  16.   
  17.     private static final String[] portArray = new String[] { "1111""2222",  
  18.             "3333" };  
  19.   
  20.     /*从文件中使用正则解析出url的部分信息,下面正则是将 以/开头的,非空白字符结尾的字符串取出,如“/abcc空格”字符串,\s为任意的空白符  */  
  21.     public static ArrayList<String> fetchUrlFromFile(String str) {  
  22.         ArrayList<String> arrayList = new ArrayList<String>();  
  23.         Pattern urlPattern = Pattern.compile("/[^\\s]+");  
  24.         //Pattern urlPattern = Pattern.compile("/[\\S]+");  
  25.         Matcher matcher = urlPattern.matcher(str);  
  26.         while (matcher.find()) {  
  27.             arrayList.add(matcher.group());  
  28.         }  
  29.         return arrayList;  
  30.     }  
  31.   
  32.     public static void main(String[] args) throws Exception {  
  33.         CountDownLatch begin = new CountDownLatch(1);  
  34.   
  35.         StringBuilder stringBuilder = new StringBuilder();  
  36.         String filePath = args[0];  
  37.         FileReader fr = new FileReader(filePath);  
  38.         BufferedReader br = new BufferedReader(fr);  
  39.         while (br.ready()) {  
  40.             stringBuilder.append(br.readLine());  
  41.         }  
  42.         String stringAll = stringBuilder.toString();  
  43.         ArrayList<String> arrayList = fetchUrlFromFile(stringAll);  
  44.         int allRequestSize = arrayList.size();  
  45.         log.info("all request size is " + allRequestSize);  
  46.         //设置最大的并发数量为60  
  47.         ExecutorService exec = Executors.newFixedThreadPool(60);  
  48.   
  49.         CountDownLatch end = new CountDownLatch(allRequestSize);  
  50. //      int i = 0;  
  51.         for (String str : arrayList) {  
  52.             exec.execute(new CallHttpRequest(portArray[0], str, begin, end));  
  53.               
  54.             /*如果想测试60个线程并发的访问,发配到同一台服务器上的两个tomcat,就用下面注释掉的代码 
  55.              * if (i % 2 == 0) { 
  56.                 exec.execute(new CallHttpRequest(portArray[0], str, begin, end)); 
  57.             } else if (i % 2 == 1) { 
  58.                 exec.execute(new CallHttpRequest(portArray[1], str, begin, end)); 
  59.             } */  
  60. //          i++;  
  61.         }  
  62.         long startTime = System.currentTimeMillis();  
  63.         //当60个线程,初始化完成后,解锁,让六十个线程在4个双核的cpu服务器上一起竞争着跑,来模拟60个并发线程访问tomcat  
  64.         begin.countDown();  
  65.   
  66.         try {  
  67.             end.await();  
  68.         } catch (InterruptedException e) {  
  69.             e.printStackTrace();  
  70.         } finally {  
  71.             log.info("all url requests is done!");  
  72.             log.info("the success size: " + CallHttpRequest.successRequest);  
  73.             log.info("the fail size: " + CallHttpRequest.failRequest);  
  74.             log.info("the timeout size: " + CallHttpRequest.timeOutRequest);  
  75.             double successRate = (double)CallHttpRequest.successRequest / allRequestSize;  
  76.             log.info("the success rate is: " + successRate*100+"%");  
  77.             long endTime = System.currentTimeMillis();  
  78.             long costTime = endTime - startTime;  
  79.             log.info("the total time cost is: " + costTime + " ms");  
  80.             log.info("every request time cost is: " + costTime / allRequestSize  
  81.                     + " ms");  
  82.         }  
  83.         exec.shutdown();  
  84.         log.info("main method end");  
  85.   
  86.     }  
  87. }  
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值