zoukankan      html  css  js  c++  java
  • jedis 连接 redis

    一、连接单机版的 redis

    /**
     * 直接连接 redis
     * @throws Exception
     */
    @Test
    public void test1() throws Exception {
        //创建一个 jedis 对象,参数:host、post
        Jedis jedis = new Jedis("192.168.25.128", 6379);
        //直接通过 jedis 操作 redis,每个 redis 命令都对应一个方法
        jedis.set("a", "hello");
        String str = jedis.get("a");
        System.out.println(str);
        //关闭连接
        jedis.close();
    }
    
    /**
     * 通过连接池连接 redis
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        //创建一个连接池对象,两个参数 host、post
        JedisPool pool = new JedisPool("192.168.25.128", 6379);
        //从连接池获得一个连接,就是一个 jedis 对象
        Jedis jedis = pool.getResource();
        //使用 jedis 操作 redis
        String str = jedis.get("a");
        System.out.println(str);
        //关闭连接(每次使用完毕后都要关闭连接)
        jedis.close();
        //关闭连接池
        pool.close();
    }

    二、连接 redis 集群

    /**
     * jedis 连接 redis 集群
     * @throws Exception
     */
    @Test
    public void test3() throws Exception{
        //创建一个 JedisCluster 对象(单例)。有一个参数 nodes,是一个 set 类型。set 中包含若干个 HostAndPort 对象
        Set<HostAndPort> nodes = new HashSet();
        nodes.add(new HostAndPort("192.168.25.128", 7001));
        nodes.add(new HostAndPort("192.168.25.128", 7002));
        nodes.add(new HostAndPort("192.168.25.128", 7003));
        nodes.add(new HostAndPort("192.168.25.128", 7004));
        nodes.add(new HostAndPort("192.168.25.128", 7005));
        nodes.add(new HostAndPort("192.168.25.128", 7006));
        JedisCluster jedisCluster = new JedisCluster(nodes);
        //直接使用 JedisCluster对象操作 redis。(JedisCluster 自带连接池,不用关闭)
        jedisCluster.set("b", "123");
        String str = jedisCluster.get("b");
        System.out.println(str);
        //系统关闭之前,关闭 JedisCluster
        jedisCluster.close();
    }

    三、开发过程中用单机版,实际才用集群版

  • 相关阅读:
    【BZOJ4445】【SCOI2015】—小凸想跑步(半平面交)
    【BZOJ4444】【SCOI2015】—国旗计划(倍增+贪心)
    【BZOJ4443】【SCOI2015】—小凸玩矩阵(二分+最大匹配)
    【BZOJ4518】【SDOI2016】—征途(斜率优化dp)
    【BZOJ4199】【NOI2015】—品酒大会(后缀数组)
    【BZOJ3160】【2013湖北互测week1】—万径人踪灭(FFT+Manacher)
    ifconfig 查看网卡信息
    rm:删除目录和文件
    查看进程:ps
    wget 下载命令
  • 原文地址:https://www.cnblogs.com/fangwu/p/8620798.html
Copyright © 2011-2022 走看看