redis paging implemented by redisTemplate in spring

Posted by jsladek on Sun, 03 Nov 2019 02:45:34 +0100

Recently, we need to cache the data in mysql table into redis, and the list display also needs to use paging to query. At first, we thought that HASH structure can meet the needs, and then we can use ZSET and HASH structure to store data to realize redis paging.

The steps are as follows:

1. First, use ZSET to store the id in table A in the form of value, and use the score in ZSET to sort.
2. Store the data in table A in HASH structure, with id as the key in HASH;
3. Use zRangeByScore in redis to perform ZSET paging and get the id list, and then get the paging data in HASH.

The code is as follows:

/**
     * Store a single hash cache
     * @param key key
     * @param hkey key
     * @param value 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;
    }
    
/**
     * Paging access data
     * @param key  hash Access key
     * @param hkey hash Accessed hkey
     * @param score Specify field sorting
     * @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;
    }
    
    /**
     * Paging out the hkey value in the hash
     * @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);//100000 represents the sort atmosphere value of score, i.e. the range from 1-100000 
            log.debug("getPage {}", key);
        } catch (Exception e) {
            log.warn("getPage {}", key, e);
        }
        return result;
    }

    /**
     * Calculate the quantity corresponding to the key value
     * @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;
    }

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Topics: Java Redis MySQL