码迷,mamicode.com
首页 > 编程语言 > 详细

java连接redis集群

时间:2017-12-09 13:02:13      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:lan   ati   exception   null   ace   target   bsp   模式   oid   

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();
    }
}

 

java连接redis集群

标签:lan   ati   exception   null   ace   target   bsp   模式   oid   

原文地址:http://www.cnblogs.com/duneF/p/8011056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!