java连接redis集群

http://m.blog.csdn.net/koushr/article/details/50956870

连接redis数据库(非集群模式)

public static void main(String[] args) {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    // 最大连接数
    poolConfig.setMaxTotal(2);
    // 最大空闲数
    poolConfig.setMaxIdle(2);
    // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
    // Could not get a resource from the pool
    poolConfig.setMaxWaitMillis(1000);
    JedisPool pool = new JedisPool(poolConfig, "192.168.83.128", 6379, 0, "123");
    Jedis jedis = null;
    try {
        for (int i = 0; i < 5; i++) {
            jedis = pool.getResource();
            jedis.set("foo" + i, "bar" + i);
            System.out.println("第" + (i + 1) + "个连接, 得到的值为" + jedis.get("foo" + i));
            // 用完一定要释放连接
            jedis.close();
        }
    } finally {
        pool.close();
    }
}

连接redisCluster(集群模式)

public static void main(String[] args) {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    // 最大连接数
    poolConfig.setMaxTotal(1);
    // 最大空闲数
    poolConfig.setMaxIdle(1);
    // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
    // Could not get a resource from the pool
    poolConfig.setMaxWaitMillis(1000);
    Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
    nodes.add(new HostAndPort("192.168.83.128", 6379));
    nodes.add(new HostAndPort("192.168.83.128", 6380));
    nodes.add(new HostAndPort("192.168.83.128", 6381));
    nodes.add(new HostAndPort("192.168.83.128", 6382));
    nodes.add(new HostAndPort("192.168.83.128", 6383));
    nodes.add(new HostAndPort("192.168.83.128", 6384));
    JedisCluster cluster = new JedisCluster(nodes, poolConfig);
    String name = cluster.get("name");
    System.out.println(name);
    cluster.set("age", "18");
    System.out.println(cluster.get("age"));
    try {
        cluster.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

posted @ 2017-12-09 11:53  dune.F  阅读(19538)  评论(0编辑  收藏  举报