• Redis基础类型ZSet增删改查(带Java库源码)


    1 缘起

    继续系统补充Redis基础数据类型操作知识。
    为帮助读者更加系统地学习Redis基础数据操作,
    分享其他数据类型操作文章:

    Redis进阶:图文讲解Redis底层数据结构之embstr,raw,ziplist,quicklist和hashtable (带源码讲解)

    注意:

    (1)文末附全部测试代码;
    (2)本篇文章将学习使用如下函数(方法):

    序号操作method
    1新增zadd,zinterstore
    2删除zrem,zremrangeByRank,zremrangeByScore
    3修改zincrby
    4查询zrange,zrangeByScore

    2 Zset测试

    Redis基础数据类型ZSet是set的另一种形式,比set的多了一个分数属性,
    可以通过分数操作相关数据,比如按照分数范围查询数据,按照分数排序,
    这也催生了skiplist的应用。
    本文采用连接池的方式直连Redis,连接池配置如下:

    • 依赖
    
    <dependency>
        <groupId>redis.clientsgroupId>
        <artifactId>jedisartifactId>
        <version>3.5.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • Redis连接池配置(可以根据需要设置为共用)
    private static JedisPool getJedisPool() {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            // Jedis池:最大连接数
            jedisPoolConfig.setMaxTotal(1);
            // Jedis池:最大空闲连接数
            jedisPoolConfig.setMaxIdle(10);
            // Jedis池:等待时间
            jedisPoolConfig.setMaxWaitMillis(3000);
            // Jedis池:连接Redis超时时间
            int connectTimeout = 2000;
            String redisHost = "127.0.0.1";
            int redisPort = 6379;
            String redisPassword = "123456";
            int redisDb = 0;
            // 创建连接池
            return new JedisPool(jedisPoolConfig, redisHost, redisPort, connectTimeout, redisPassword, redisDb);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.1 新增数据

    zset新增数据有两种方式:直接新增以及取交新增。
    其中,直接新增有:单条新增和批量新增;
    取交新增是取两个zset的交集,新增到新的zset中。

    2.1.1 直接新增:zadd

    单条新增是通过key、score和value方式进行;
    批量新增是通过key,map(数据的score和value映射)进行。
    测试样例如下:

    /**
         * 新增数据.
         */
        @Test
        public void insertData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 单条插入:带分数
                Long res1 = jedis.zadd("zsetziplist", 2, "xiaohua");
                Long res2 = jedis.zadd("zsetziplist", 1, "xiaolan");
                Long res3 = jedis.zadd("zsetziplist", 3, "xiaoti");
                Map<String, Double> scoreMembersMap = new HashMap<>();
                scoreMembersMap.put("xiaohei", 0.1);
                scoreMembersMap.put("xiaobai", 0.02);
                scoreMembersMap.put("xiaoniu", 0.5);
                // 批量插入:带分数
                Long res4 = jedis.zadd("zsetziplist", scoreMembersMap);
                logger.info(">>>>>>>>插入zset:{}, {}, {}, {}", res1, res2, res3, res4);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>插入zset异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    单条新增的源码如下图所示,
    由图可知,时间复杂度为 O ( l o g ( N ) ) O(log(N)) O(log(N)),当在某个zset中不存在添加的数据时,则新增,
    若存在,则更新当前value的分数(score),如zset a,在a中添加数据:(xiaohua,1),
    如果a中不存在该数据,则新增该数据到a中,
    如果a中已存在(xiaohua, 0),则更新xiaohua的值为1。
    在这里插入图片描述
    当然,Redis库提供了批量添加数据的方式,
    将value和score映射存储到Map中,一次性存储,
    源码如下图所示,没有注释,不过按照测试结果可知,是通过Map添加数据。
    在这里插入图片描述

    2.1.2 取交集新建集合:zinterstore

    既然zset是变种的集合,当然有交集的概念,
    zset取多个zset的交集可以新建zset,
    如zset a和zset b,取a和b的交集,生成新的zset c,
    c的中value的score为a和b中对应value score的和。
    同时,zinterstore提供了按照权重聚合方法,
    使用ZParams的weights的方法,为对应zset score提供权重值,
    即合并前,每个zset的score先乘以权重,然后在取交集,求和,
    其中,ZParams中权重的数量应与待取交集的zset数量一致,为每个zset提供一个权重。
    测试样例如下:

        /**
         * 取交集,新建集合.
         */
        @Test
        public void unionAndCreateZSetData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                Map<String, Double> scoreMembersMap = new HashMap<>();
                scoreMembersMap.put("xiaohei", 0.1);
                scoreMembersMap.put("xiaobai", 0.02);
                scoreMembersMap.put("xiaoniu", 0.5);
                Map<String, Double> scoreMembersMap1 = new HashMap<>();
                scoreMembersMap1.put("xiaohei", 0.21);
                scoreMembersMap1.put("xiaobai", 0.05);
                scoreMembersMap1.put("xiaobu", 0.5);
                // 批量插入:带分数
                Long res1 = jedis.zadd("zsetziplist-1", scoreMembersMap);
                Long res2 = jedis.zadd("zsetziplist-2", scoreMembersMap1);
                // 取zset:zsetziplist-1, zsetziplist-2;交集,新建zset:zsetziplist-union
                Long res3 = jedis.zinterstore("zsetziplist-union", "zsetziplist-1", "zsetziplist-2");
    
                Map<String, Double> scoreMembersMap3 = new HashMap<>();
                scoreMembersMap3.put("xiaohei", 0.1);
                scoreMembersMap3.put("xiaobai", 0.02);
                scoreMembersMap3.put("xiaoniu", 0.5);
                Map<String, Double> scoreMembersMap4 = new HashMap<>();
                scoreMembersMap4.put("xiaohei", 0.21);
                scoreMembersMap4.put("xiaobai", 0.05);
                scoreMembersMap4.put("xiaobu", 0.5);
                // 批量插入:带分数
                Long res4 = jedis.zadd("zsetziplist-3", scoreMembersMap3);
                Long res5 = jedis.zadd("zsetziplist-4", scoreMembersMap4);
                // 使用weight
                ZParams zParams = new ZParams();
                zParams.weights(3, 5);
                Long res6 = jedis.zinterstore("zset-weight", zParams, "zsetziplist-3", "zsetziplist-4");
                logger.info(">>>>>>>>插入zset:{}, {}, {}, {}, {}, {}", res1, res2, res3, res4, res5, res6);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>插入zset异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    zinterstore源码如下图所示,
    由源码可知,时间复杂度为 O ( n ) + O ( m l o g m ) O(n)+O(mlogm) O(n)+O(mlogm),其中,n为待取交集的set集合的数据量,m为结果集合的数据量。
    取交集的过程中,如果使用带权重的方法,合并前会先将zset中的score先乘以权重,
    然后再合并求和。
    在这里插入图片描述

    2.2 删除数据

    zset删除数据数据有三种方式:
    (1)直接删除:zrem;
    (2)按照顺序批量删除:zremrangeByRank;
    (3)按照score范围删除:zremrangeByScore;
    测试样例如下:

    /**
         * 删除数据.
         */
        @Test
        public void deleteData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 删除指定数据
                Long res1 = jedis.zrem("zsetziplist", "xiaobai");
                // 根据索引范围删除数据
                Long res2 = jedis.zremrangeByRank("zsetziplist", 0, 1);
                // 根据score范围删除数据
                Long res3 = jedis.zremrangeByScore("zsetziplist", 0, 2);
                logger.info(">>>>>>>>删除:{}, {}, {}", res1, res2, res3);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset删除异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.2.1 zrem

    直接删除源码如下,由源码可知,
    时间复杂度为 O ( l o g n ) O(logn) O(logn),zset中有该值,则按照对应的数据删除,没有则不操作。
    在这里插入图片描述

    2.2.2 zremrangeByRank

    按照数据排序批量删除源码如下,
    由于zset的数据是按照score排序存储的,
    因此,天然可以按照排名批量删除数据。
    有源码可知,时间复杂度为 O ( l o g n ) + O ( m ) O(logn)+O(m) O(logn)+O(m),其中,n为zset的原始数据数量,m为删除元素的数量。
    排序范围:[0,n],当然,也可为负数,倒序删除。
    在这里插入图片描述

    2.2.3 zremrangeByScore

    根据score范围删除,也是zset的一个天然方法,
    源码如下图所示,由源码中,时间复杂度为 O ( l o g n ) + O ( m ) O(logn)+O(m) O(logn)+O(m),其中,其中,n为zset的原始数据数量,m为删除元素的数量。
    score范围比较随意,按照需要填写即可。
    在这里插入图片描述

    2.3 修改数据

    Redis的set是没有修改操作的,因为,set只存储value,
    而zset当然也不支持修改value,这里的修改数据,是修改score,
    测试样例如下:

    /**
         * 修改数据.
         */
        @Test
        public void editData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 修改score
                Double res1 = jedis.zincrby("zsetziplist", 1, "xiaoniu");
                logger.info(">>>>>>>>编辑:{}, {}", res1);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset编辑异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    修改score源码如下图所示,
    由源码知,时间复杂度为 O ( l o g n ) O(logn) O(logn)
    修改zset某个value的score时,如果value存在,则直接修改,
    如果不存在value,则新增该数据。
    在这里插入图片描述

    2.4 查询数据

    查询zset数据,由于zset特有的数据设计,
    有两种常用的查询方式:
    (1)根据索引查询:zrange;
    (2)根据分数范围查询:zrangeByScore;
    测试样例如下:

    /**
         * 查询数据.
         */
        @Test
        public void queryData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 指定索引范围查询
                Set<String> res1 = jedis.zrange("zsetziplist", 0, 1);
                // 根据分数范围查询
                Set<String> res2 = jedis.zrangeByScore("zsetziplist", 2, 3);
                logger.info(">>>>>>>>查询zset:{},{}", res1, res2);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset查询异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2.4.1 zrange

    根据索引范围查询,源码如下图所示,
    由源码知没有注释,按照测试结果,
    zrange是根据索引范围查询。
    在这里插入图片描述

    2.4.2 zrangeByScore

    zset的设计有score这个属性,
    当然不能浪费,查询时按照分数范围查询
    源码如下图所示,由源码知,时间复杂度为 O ( m ) O(m) O(m)
    score范围是闭区间匹配,该方法类似于SQL的LIMIT语句。
    在这里插入图片描述
    在这里插入图片描述

    3 小结

    zset增删改查汇总:

    序号操作method
    1新增zadd,zinterstore
    2删除zrem,zremrangeByRank,zremrangeByScore
    3修改zincrby
    4查询zrange,zrangeByScore

    为帮助读者更加系统地学习Redis基础数据操作,
    分享其他数据类型操作文章:

    Redis进阶:图文讲解Redis底层数据结构之embstr,raw,ziplist,quicklist和hashtable (带源码讲解)

    附件

    package database_test.redis_test;
    
    import org.junit.Test;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * zset测试.
     *
     * @author xindaqi
     * @since 2022-08-18 15:31
     */
    public class ZSetTest {
    
        private static final Logger logger = LoggerFactory.getLogger(ZSetTest.class);
    
        private static JedisPool getJedisPool() {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            // Jedis池:最大连接数
            jedisPoolConfig.setMaxTotal(1);
            // Jedis池:最大空闲连接数
            jedisPoolConfig.setMaxIdle(10);
            // Jedis池:等待时间
            jedisPoolConfig.setMaxWaitMillis(3000);
            // Jedis池:连接Redis超时时间
            int connectTimeout = 2000;
            String redisHost = "127.0.0.1";
            int redisPort = 6379;
            String redisPassword = "123456";
            int redisDb = 0;
            // 创建连接池
            return new JedisPool(jedisPoolConfig, redisHost, redisPort, connectTimeout, redisPassword, redisDb);
        }
    
        /**
         * 新增数据.
         */
        @Test
        public void insertData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 单条插入:带分数
                Long res1 = jedis.zadd("zsetziplist", 2, "xiaohua");
                Long res2 = jedis.zadd("zsetziplist", 1, "xiaolan");
                Long res3 = jedis.zadd("zsetziplist", 3, "xiaoti");
                Map<String, Double> scoreMembersMap = new HashMap<>();
                scoreMembersMap.put("xiaohei", 0.1);
                scoreMembersMap.put("xiaobai", 0.02);
                scoreMembersMap.put("xiaoniu", 0.5);
                // 批量插入:带分数
                Long res4 = jedis.zadd("zsetziplist", scoreMembersMap);
                logger.info(">>>>>>>>插入zset:{}, {}, {}, {}", res1, res2, res3, res4);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>插入zset异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
        /**
         * 取交集,新建集合.
         */
        @Test
        public void unionAndCreateZSetData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                Map<String, Double> scoreMembersMap = new HashMap<>();
                scoreMembersMap.put("xiaohei", 0.1);
                scoreMembersMap.put("xiaobai", 0.02);
                scoreMembersMap.put("xiaoniu", 0.5);
                Map<String, Double> scoreMembersMap1 = new HashMap<>();
                scoreMembersMap1.put("xiaohei", 0.21);
                scoreMembersMap1.put("xiaobai", 0.05);
                scoreMembersMap1.put("xiaobu", 0.5);
                // 批量插入:带分数
                Long res1 = jedis.zadd("zsetziplist-1", scoreMembersMap);
                Long res2 = jedis.zadd("zsetziplist-2", scoreMembersMap1);
                // 取zset:zsetziplist-1, zsetziplist-2;交集,新建zset:zsetziplist-union
                Long res3 = jedis.zinterstore("zsetziplist-union", "zsetziplist-1", "zsetziplist-2");
                logger.info(">>>>>>>>插入zset:{}, {}, {}", res1, res2, res3);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>插入zset异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
        /**
         * 删除数据.
         */
        @Test
        public void deleteData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 删除指定数据
                Long res1 = jedis.zrem("zsetziplist", "xiaobai");
                // 根据索引范围删除数据
                Long res2 = jedis.zremrangeByRank("zsetziplist", 0, 1);
                // 根据score范围删除数据
                Long res3 = jedis.zremrangeByScore("zsetziplist", 0, 2);
                logger.info(">>>>>>>>删除:{}, {}, {}", res1, res2, res3);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset删除异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
        /**
         * 修改数据.
         */
        @Test
        public void editData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 修改score
                Double res1 = jedis.zincrby("zsetziplist", 1, "xiaoniu");
                logger.info(">>>>>>>>编辑:{}, {}", res1);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset编辑异常", ex);
                throw new RuntimeException(ex);
            }
        }
    
        /**
         * 查询数据.
         */
        @Test
        public void queryData() {
            try (Jedis jedis = getJedisPool().getResource()) {
                // 指定索引范围查询
                Set<String> res1 = jedis.zrange("zsetziplist", 0, 1);
                // 根据分数范围查询
                Set<String> res2 = jedis.zrangeByScore("zsetziplist", 2, 3);
                logger.info(">>>>>>>>查询zset:{},{}", res1, res2);
            } catch (Exception ex) {
                logger.error(">>>>>>>>>Redis zset查询异常", ex);
                throw new RuntimeException(ex);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
  • 相关阅读:
    mybatis拦截器源码分析
    JDK19都出来了~是时候梳理清楚JDK的各个版本的特性了【JDK9特性讲解】
    国债1万亿,你该学点什么
    用CHAT写APP的权限需求
    沙丁鱼优化算法(Sardine optimization algorithm,SOA)求解23个函数MATLAB
    华为机试:连续出牌数量
    人与机器
    30天入门Python(基础篇)——第1天:为什么选择Python
    springMVC入门案例
    MySQL索引
  • 原文地址:https://blog.csdn.net/Xin_101/article/details/126928319