package com.jd.redis.client; import java.util.concurrent.CountDownLatch; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; publicclass JedisPoolTest { privatestatic JedisPoolConfigconfig;//Jedis用戶端池配置 privatestatic JedisPoolpool;//Jedis用戶端池 static{ config =new JedisPoolConfig(); config.setMaxActive(60000); config.setMaxIdle(1000); config.setMaxWait(10000); config.setTestOnBorrow(true); pool =new JedisPool(config,"192.168.157.128", 6380); } /** * 單筆測試(不用池) * @param count */ publicstaticvoid testNoPool(int count){ for(int i=0;i<count;i++){ Jedis jr = null; try { jr = new Jedis("10.10.224.44", 6379); testOnce(jr); } catch (Exception e) { e.printStackTrace(); } finally{ if(jr!=null)jr.disconnect(); } } } /** * 單筆測試(用池) * @param count */ publicstaticvoid testWithPool(int count){ for(int i=0;i<count;i++){ Jedis jr = null; try { jr = pool.getResource(); testOnce(jr); } catch (Exception e) { e.printStackTrace(); } finally{ if(jr!=null)pool.returnResource(jr); } } } /** * 並發測試(不用池) * @param paiallel並發量 * @param count每個並發迴圈次數 */ publicstaticvoid paiallelTestNoPool(int paiallel, int count){ Thread[] ts = new Thread[paiallel]; //用該對象保證所線程都完成主線程才退出 CountDownLatch cd = new CountDownLatch(paiallel); long start = System.currentTimeMillis(); for(int i=0; i < paiallel; i++){ ts[i] = new Thread(new WorkerNoPool(cd, count)); ts[i].start(); } try { cd.await();//等待所有子線程完成 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("NoPool useTime:"+ (System.currentTimeMillis() - start)); } /** * 並發測試(用池) * @param paiallel並發量 * @param count每個並發迴圈次數 */ publicstaticvoid paiallelTestWithPool(int paiallel, int count){ //用該對象保證所線程都完成主線程才退出 CountDownLatch cd = new CountDownLatch(paiallel); long start = System.currentTimeMillis(); Thread[] ts = new Thread[paiallel]; for(int i=0; i < paiallel; i++){ ts[i] = new Thread(new WorkerWithPool(cd, count)); ts[i].start(); } try { cd.await();//等待所有子線程完成 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Pool useTime:"+ (System.currentTimeMillis() - start)); pool.destroy(); } privatestaticvoid testOnce(Jedis jr){ System.out.println(jr.incr("incrTest")); } publicstaticclass WorkerNoPoolimplements Runnable{ private CountDownLatchcd; privateintcount; public WorkerNoPool(CountDownLatch cd,int count){ this.cd = cd; this.count = count; } publicvoid run() { try { testNoPool(this.count); } catch (Exception e) { |