ShardedJedisPool的使用

 1 package com.test;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import redis.clients.jedis.JedisPoolConfig;
 7 import redis.clients.jedis.JedisShardInfo;
 8 import redis.clients.jedis.ShardedJedis;
 9 import redis.clients.jedis.ShardedJedisPool;
10 
11 public class RedisShardPoolTest {
12     
13     static ShardedJedisPool pool;
14 
15     static{
16         JedisPoolConfig config =new JedisPoolConfig();//Jedis池配置
17         config.setMaxActive(500);//最大活动的对象个数
18         config.setMaxIdle(1000 * 60);//对象最大空闲时间
19         config.setMaxWait(1000 * 10);//获取对象时最大等待时间
20         config.setTestOnBorrow(true);
21         String hostA = "192.168.0.100";
22         int portA = 6379;
23         String hostB = "192.168.0.115";
24         int portB = 6379;
25         List<JedisShardInfo> jdsInfoList =new ArrayList<JedisShardInfo>(2);
26         JedisShardInfo infoA = new JedisShardInfo(hostA, portA);
27         infoA.setPassword("admin");
28         JedisShardInfo infoB = new JedisShardInfo(hostB, portB);
29         infoB.setPassword("admin");
30         jdsInfoList.add(infoA);
31         jdsInfoList.add(infoB);
32         pool =new ShardedJedisPool(config, jdsInfoList);
33      }
34 
35        
36 
37     /**
38     
39      * @param args
40     
41      */
42     
43     public static void main(String[] args) {
44         for(int i=0; i<100; i++){
45             String key = generateKey();
46             ShardedJedis jds = null;
47             try {
48                 jds = pool.getResource();
49                 System.out.println(key+":"+jds.getShard(key).getClient().getHost());
50                 System.out.println(jds.set(key,Math.random()+""));
51             } catch (Exception e) {
52                 e.printStackTrace();
53             } finally {
54                 pool.returnResource(jds);
55             }
56         }
57     }
58     
59     private static int index = 1;
60     public static String generateKey(){
61         return String.valueOf(Thread.currentThread().getId())+"_"+(index++);
62     }
63 }

 

posted @ 2014-04-21 21:02  残剑_  阅读(29159)  评论(0编辑  收藏  举报