轻松把玩HttpClient之封装HttpClient工具类(四),单线程调用及多线程批量调用测试

简介:        本文主要来分享一下该工具类的测试结果。工具类的整体源码不再单独分享,源码基本上都已经在文章中了。开始我们的测试。       单线程调用测试: public static void testOne() throws HttpProcessException{ System.

       本文主要来分享一下该工具类的测试结果。工具类的整体源码不再单独分享,源码基本上都已经在文章中了。开始我们的测试。

       单线程调用测试:

	public static void testOne() throws HttpProcessException{
		
		System.out.println("--------简单方式调用(默认post)--------");
		String url = "http://tool.oschina.net/";
		//简单调用
		String resp = HttpClientUtil.send(url);
		System.out.println("请求结果内容长度:"+ resp.length());
		
		System.out.println("\n#################################\n");
		
		System.out.println("--------加入header设置--------");
		url="http://blog.csdn.net/xiaoxian8023";
		//设置header信息
		Header[] headers=HttpHeader.custom().userAgent("Mozilla/5.0").build();
		//执行请求
		resp = HttpClientUtil.send(url, headers);
		System.out.println("请求结果内容长度:"+ resp.length());

		System.out.println("\n#################################\n");
		
		System.out.println("--------代理设置(绕过证书验证)-------");
		url="https://www.facebook.com/";
		HttpClient client= HCB.custom().timeout(10000).proxy("127.0.0.1", 8087).ssl().build();//采用默认方式(绕过证书验证)
		//执行请求
		resp = HttpClientUtil.send(client,url);
		System.out.println("请求结果内容长度:"+ resp.length());

		System.out.println("\n#################################\n");

		System.out.println("--------代理设置(自签名证书验证)+header+get方式-------");
		url = "https://sso.tgb.com:8443/cas/login";
		client= HCB.custom().timeout(10000).ssl("D:\\keys\\wsriakey","tomcat").build();
		headers=HttpHeader.custom().keepAlive("false").connection("close").contentType(Headers.APP_FORM_URLENCODED).build();
		//执行请求
		resp = HttpClientUtil.send(client, url, HttpMethods.GET, headers);
		System.out.println("请求结果内容长度:"+ resp.length());

		System.out.println("\n#################################\n");
	}
       测试结果如下:


       可以看到4次调用,都没有问题。

       那么现在试试多线程调用吧。我定义一个数组,里面有20篇文章的地址。我启动20个线程的线程池来测试,写了一个20*50次的for循环,看看全部线程结束时有没有报错,能用多长时间:

	public static void testMutilTask(){
		// URL列表数组
		String[] urls = {
				"http://blog.csdn.net/xiaoxian8023/article/details/49862725",
				"http://blog.csdn.net/xiaoxian8023/article/details/49834643",
				"http://blog.csdn.net/xiaoxian8023/article/details/49834615",
				"http://blog.csdn.net/xiaoxian8023/article/details/49834589",
				"http://blog.csdn.net/xiaoxian8023/article/details/49785417",
				
				"http://blog.csdn.net/xiaoxian8023/article/details/48679609",
				"http://blog.csdn.net/xiaoxian8023/article/details/48681987",
				"http://blog.csdn.net/xiaoxian8023/article/details/48710653",
				"http://blog.csdn.net/xiaoxian8023/article/details/48729479",
				"http://blog.csdn.net/xiaoxian8023/article/details/48733249",

				"http://blog.csdn.net/xiaoxian8023/article/details/48806871",
				"http://blog.csdn.net/xiaoxian8023/article/details/48826857",
				"http://blog.csdn.net/xiaoxian8023/article/details/49663643",
				"http://blog.csdn.net/xiaoxian8023/article/details/49619777",
				"http://blog.csdn.net/xiaoxian8023/article/details/47335659",

				"http://blog.csdn.net/xiaoxian8023/article/details/47301245",
				"http://blog.csdn.net/xiaoxian8023/article/details/47057573",
				"http://blog.csdn.net/xiaoxian8023/article/details/45601347",
				"http://blog.csdn.net/xiaoxian8023/article/details/45569441",
				"http://blog.csdn.net/xiaoxian8023/article/details/43312929", 
				};
		
		// 设置header信息
		Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0").build();
		HttpClient client= HCB.custom().timeout(10000).build();
		
		 long start = System.currentTimeMillis();        
	        try {
	            int pagecount = urls.length;
	            ExecutorService executors = Executors.newFixedThreadPool(pagecount);
	            CountDownLatch countDownLatch = new CountDownLatch(pagecount*100);         
	            for(int i = 0; i< pagecount*100;i++){
	                //启动线程抓取
	                executors.execute(new GetRunnable(urls[i%pagecount], headers, countDownLatch).setClient(client));
	            }
	            countDownLatch.await();
	            executors.shutdown();
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        } finally {
	            System.out.println("线程" + Thread.currentThread().getName() + ", 所有线程已完成,开始进入下一步!");
	        }
	         
	        long end = System.currentTimeMillis();
	        System.out.println("总耗时(毫秒): -> " + (end - start));
	        //(7715+7705+7616)/3= 23 036/3= 7 678.66---150=51.2
	        //(9564+8250+8038+7604+8401)/5=41 857/5=8 371.4--150
	        //(9803+8244+8188+8378+8188)/5=42 801/5= 8 560.2---150
	}
	
	 static class GetRunnable implements Runnable {
	        private CountDownLatch countDownLatch;
	        private String url;
	        private Header[] headers;
	        private HttpClient client = null;
	        
	        public GetRunnable setClient(HttpClient client){
	        	this.client = client;
	        	return this;
	        }

	        public GetRunnable(String url, Header[] headers,CountDownLatch countDownLatch){
	        	this.url = url;
	        	this.headers = headers;
	            this.countDownLatch = countDownLatch;
	        }
	        @Override
	        public void run() {
	            try {
	            	String response = null;
	            	if(client!=null){
	            		response = HttpClientUtil.send(client, url, headers);
	            	}else{
	            		response =  HttpClientUtil.send(url, headers);
	            	}
	            	System.out.println(Thread.currentThread().getName()+"--获取内容长度:"+response.length());
	            } catch (HttpProcessException e) {
					e.printStackTrace();
				} finally {
	                countDownLatch.countDown();
	            }
	        }
	    } 

       定义了一个ExecutorService的线程池,使用CountDownLatch来保证所有线程都运行完毕,测试一下看看:

	public static void main(String[] args) throws Exception {
//		testOne();
		testMutilTask();
	}
       测试结果如下:

       从结果中可以清楚的看到执行1000次调用,总消耗是51165,平均51ms/个,速度快,而且没有报错。

       好了,本工具就分享到这里,下次会分享异步的HttpClient,敬请期待。


       代码已上传https://github.com/Arronlong/httpclientUtil

       httpclientUtil (QQ交流群:548452686 httpclientUtil交流

目录
相关文章
|
2月前
|
存储 监控 Java
Java多线程优化:提高线程池性能的技巧与实践
Java多线程优化:提高线程池性能的技巧与实践
64 1
|
6天前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
|
14天前
|
Java Spring
spring多线程实现+合理设置最大线程数和核心线程数
本文介绍了手动设置线程池时的最大线程数和核心线程数配置方法,建议根据CPU核数及程序类型(CPU密集型或IO密集型)来合理设定。对于IO密集型,核心线程数设为CPU核数的两倍;CPU密集型则设为CPU核数加一。此外,还讨论了`maxPoolSize`、`keepAliveTime`、`allowCoreThreadTimeout`和`queueCapacity`等参数的设置策略,以确保线程池高效稳定运行。
77 10
spring多线程实现+合理设置最大线程数和核心线程数
|
22天前
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android多线程编程的重要性及其实现方法,涵盖了基本概念、常见线程类型(如主线程、工作线程)以及多种多线程实现方式(如`Thread`、`HandlerThread`、`Executors`、Kotlin协程等)。通过合理的多线程管理,可大幅提升应用性能和用户体验。
38 15
一个Android App最少有几个线程?实现多线程的方式有哪些?
|
8天前
|
Python
5-5|python开启多线程入口必须在main,从python线程(而不是main线程)启动pyQt线程有什么坏处?...
5-5|python开启多线程入口必须在main,从python线程(而不是main线程)启动pyQt线程有什么坏处?...
|
24天前
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android应用开发中的多线程编程,涵盖基本概念、常见实现方式及最佳实践。主要内容包括主线程与工作线程的作用、多线程的多种实现方法(如 `Thread`、`HandlerThread`、`Executors` 和 Kotlin 协程),以及如何避免内存泄漏和合理使用线程池。通过有效的多线程管理,可以显著提升应用性能和用户体验。
38 10
|
5天前
|
NoSQL 网络协议 Unix
1)Redis 属于单线程还是多线程?不同版本之间有什么区别?
1)Redis 属于单线程还是多线程?不同版本之间有什么区别?
16 1
|
6天前
|
Java
COMATE插件实现使用线程池高级并发模型简化多线程编程
本文介绍了COMATE插件的使用,该插件通过线程池实现高级并发模型,简化了多线程编程的过程,并提供了生成结果和代码参考。
|
1月前
|
存储 Ubuntu Linux
C语言 多线程编程(1) 初识线程和条件变量
本文档详细介绍了多线程的概念、相关命令及线程的操作方法。首先解释了线程的定义及其与进程的关系,接着对比了线程与进程的区别。随后介绍了如何在 Linux 系统中使用 `pidstat`、`top` 和 `ps` 命令查看线程信息。文档还探讨了多进程和多线程模式各自的优缺点及适用场景,并详细讲解了如何使用 POSIX 线程库创建、退出、等待和取消线程。此外,还介绍了线程分离的概念和方法,并提供了多个示例代码帮助理解。最后,深入探讨了线程间的通讯机制、互斥锁和条件变量的使用,通过具体示例展示了如何实现生产者与消费者的同步模型。
下一篇
无影云桌面