美文网首页
spring中redisTemplate实现redis分页

spring中redisTemplate实现redis分页

作者: Good龙辉 | 来源:发表于2019-10-31 10:02 被阅读0次

    最近遇到需要将mysql表中数据缓存到redis中,而列表展示还需要采用分页来进行查询;最开始以为HASH结构能满足,后经网上查阅,利用ZSET及HASH结构存储数据即可实现redis分页。

    步骤如下:
    1. 首先利用ZSET将表A中的id以value形式进行存储,以及利用ZSET中score进行排序处理;
    2. 将表A中数据以HASH结构进行存储,id作为HASH中key;
    3. 利用redis中的zRangeByScore进行ZSET分页取出id列表,然后即可取出HASH中分页后的数据。

    代码如下:

    /**
         * 存放单个hash缓存
         * @param key 键
         * @param hkey 键
         * @param value 值
         * @return
         */
        public static boolean hput(String key, String hkey, Object value) {
            try {
                redisTemplate.opsForHash().put(key, hkey, value);
                log.debug("hput {} = {}", key+hkey, value);
                return true;
            } catch (Exception e) {
                log.warn("hput {} = {}", key+hkey, value, e);
            }
            return false;
        }
        
    /**
         * 分页存取数据
         * @param key  hash存取的key
         * @param hkey hash存取的hkey
         * @param score 指定字段排序
         * @param value
         * @return
         */
        public static boolean setPage(String key, String hkey, double score, String value){
            boolean result = false;
            try {
                redisTemplate.opsForZSet().add(key+":page", hkey, score);
                result = hput(key, hkey, value);
                log.debug("setPage {}", key);
            } catch (Exception e) {
                log.warn("setPage {}", key, e);
            }
            return result;
        }
        
        /**
         * 分页取出 hash中hkey值
         * @param key
         * @param offset
         * @param count
         * @return
         */
        public static Set<String> getPage(String key, int offset, int count){
            Set<String> result = null;
            try {
                result = redisTemplate.opsForZSet().rangeByScore(key+":page", 1, 100000, (offset-1)*count, count);//1 100000代表score的排序氛围值,即从1-100000的范围 
                log.debug("getPage {}", key);
            } catch (Exception e) {
                log.warn("getPage {}", key, e);
            }
            return result;
        }
    
        /**
         * 计算key值对应的数量
         * @param key
         * @return
         */
        public static Integer getSize(String key){
            Integer num = 0;
            try {
                Long size = redisTemplate.opsForZSet().zCard(key+":page");
                log.debug("getSize {}", key);
                return size.intValue();
            } catch (Exception e) {
                log.warn("getSize {}", key, e);
            }
            return num;
        }
    

    本文由博客一文多发平台 OpenWrite 发布!

    相关文章

      网友评论

          本文标题:spring中redisTemplate实现redis分页

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