美文网首页
redis使用

redis使用

作者: xiang205012 | 来源:发表于2018-06-14 23:41 被阅读40次

    导入redis连接jar包

            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.7.2</version>
            </dependency>
    
    测试1:
        @Test
        public void testJedis() throws Exception{
            // 创建Jedis连接对象,参数:host、port
            Jedis jedis = new Jedis("192.168.157.4",6379);
            // 直接使用jedis操作redis,所有jedis方法都对应redis命令
            jedis.set("test1","aaaa");
            String value = jedis.get("test1");
            System.out.println(value);
            // 每次使用完都要及时关闭
            jedis.close();
        }
    

    报错:redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
    解决办法:redis配置文件中默认绑定只能本机连接,将它注释掉


    redis连接失败.png

    重启,再试,接着报另一个错:

    redis.clients.jedis.exceptions.JedisDataException: 
    DENIED Redis is running in protected mode because protected mode is enabled, 
    no bind address was specified,no authentication password is requested to 
    clients. In this mode connections are only accepted from the loopback interface. 
    If you want to connect from external computers to Redis 
    you may adopt one of the following solutions: 1) Just disable protected mode 
    sending the command 'CONFIG SET protected-mode no' from the loopback interface 
    by connecting to Redis from the same host the server is running, however MAKE SURE Redis is 
    not publicly accessible from internet if you do so. Use CONFIG REWRITE to 
    make this change permanent. 2) Alternatively you can just disable the protected 
    mode by editing the Redis configuration file, and setting the protected mode 
    option to 'no', and then restarting the server. 3) If you started the server manually 
    just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind 
    address or an authentication password. NOTE: You only need to do one of the 
    above things in order for the server to start accepting connections from the 
    outside.
    错误的解决办法就是它的翻译:
    

    错误的解决办法就是它的翻译:

    redis.clients.jedis.exceptions.JedisDataException:
    拒绝Redis以受保护模式运行,因为启用了保护模式,未指定绑定地址,未向客户端请求验证密码。
    在这种模式下,连接只能从回送接口接受。如果要从外部计算机连接到Redis,
    您可以采用以下解决方案之一:
       1)只需禁用保护模式,即可通过从同一主机连接到Redis,
          从回送接口发送命令'CONFIG SET protected-mode no'正在运行,
          但如果你这样做,MAKE SURE Redis不能从互联网公开访问。
          使用CONFIG REWRITE使此更改永久生效。
       2)或者,您可以通过编辑Redis配置文件并将保护模式选项设置为'no'来禁用保护模式,然后重新启动服务器。 
       3)如果您只是为了测试而手动启动服务器,请使用' - 保护模式否'选项重启它。 
       4)设置绑定地址或认证密码。注意:您只需执行上述任一操作即可让服务器开始接受来自外部的连接。
    
    测试二:
        @Test
        public void testJedisPool() throws Exception{
            // 创建一个连接池对象,两个参数host、port
            JedisPool jedisPool = new JedisPool("192.168.157.4",6379);
            // 从连接池中获得一个连接,就是一个jedis对象
            Jedis jedis = jedisPool.getResource();
            jedis.set("test2","bbbb");
            String result = jedis.get("test2");
            System.out.println(result);
            // 关闭连接
            jedis.close();
            // 关闭连接池
            jedisPool.close();
        }
    
    为什么使用连接池?

        首先Redis也是一种数据库,它基于C/S模式,因此如果需要使用必须建立连接,稍微熟悉网络的人应该都清楚地知道为什么需要建立连接,C/S模式本身就是一种远程通信的交互模式,因此Redis服务器可以单独作为一个数据库服务器来独立存在。假设Redis服务器与客户端分处在异地,虽然基于内存的Redis数据库有着超高的性能,但是底层的网络通信却占用了一次数据请求的大量时间,因为每次数据交互都需要先建立连接,假设一次数据交互总共用时30ms,超高性能的Redis数据库处理数据所花的时间可能不到1ms,也即是说前期的连接占用了29ms,连接池则可以实现在客户端建立多个链接并且不释放,当需要使用连接的时候通过一定的算法获取已经建立的连接,使用完了以后则还给连接池,这就免去了数据库连接所占用的时间。

    连接池还有一堆配置,待日后慢慢研究。

    测试三:Redis集群测试
        @Test
        public void testJedisCluster() throws Exception {
            //创建一个JedisCluster对象。有一个参数nodes是一个set类型。set中包含若干个HostAndPort对象。
            Set<HostAndPort> nodes = new HashSet<>();
            nodes.add(new HostAndPort("192.168.157.4", 7001));
            nodes.add(new HostAndPort("192.168.157.4", 7002));
            nodes.add(new HostAndPort("192.168.157.4", 7003));
            nodes.add(new HostAndPort("192.168.157.4", 7004));
            nodes.add(new HostAndPort("192.168.157.4", 7005));
            nodes.add(new HostAndPort("192.168.157.4", 7006));
            JedisCluster jedisCluster = new JedisCluster(nodes);
            //直接使用JedisCluster对象操作redis。
            jedisCluster.set("test", "123");
            String string = jedisCluster.get("test");
            System.out.println(string);
            //关闭JedisCluster对象
            jedisCluster.close();
        }
    
    测试四:缓存同步

    这里分两种情况:

    • 在客户端管理页面向数据库添加时将缓存清除,然后查询时就会去查数据库,然后再次放入缓存达到同步效果
        // 客户端管理页面添加数据
        @Override
        public void addUser(User user) {
            //将数据插入到数据库表
            user.setCreated(new Date());
            user.setUpdated(new Date());
            //插入到数据库
            userMapper.insert(user);
            //缓存同步,删除缓存中对应的数据。
            jedisClient.hdel(USER_LIST, user.getUserId().toString());
        }
    
        /**
         * 客户端查询数据列表
         * 根据id查询
         * @param id
         * @return
         */
        @Override
        public List<User> getUserListByid(long id) {
            //查询缓存
            try {
                //如果缓存中有直接响应结果
                String json = jedisClient.hget(USER_LIST, cid + "");
                if (StringUtils.isNotBlank(json)) {
                    List<User> list = JsonUtils.jsonToList(json, User.class);
                    return list;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //如果没有查询数据库
            TUserExample example = new UserExample();
            Criteria criteria = example.createCriteria();
            //设置查询条件
            criteria.andCategoryIdEqualTo(cid);
            //执行查询
            List<User> list = contentMapper.selectByExampleWithBLOBs(example);
            //把结果添加到缓存
            try {
                jedisClient.hset(USER_LIST, cid + "", JsonUtils.objectToJson(list));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
    
    • 直接在数据库添加,此时该如何同步呢

    相关文章

      网友评论

          本文标题:redis使用

          本文链接:https://www.haomeiwen.com/subject/nayueftx.html