当前位置: 首页 > news >正文

RedissonClient:ZSet(有序集合)上手教程

介绍:

RedissonClient 是 Redisson 提供的 Java 客户端,用于操作 Redis 数据。ZSet(有序集合)是 Redis 中的一种数据结构,它存储一组唯一的元素,并为每个元素分配一个分数(score),元素根据分数排序。以下是 RedissonClient 操作 ZSet 的详细教程。

使用步骤

1. 添加依赖

首先,确保项目中引入了 Redisson 的依赖。如果使用 Maven,可以在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.20.0</version> <!-- 请使用最新版本 -->
</dependency>

2. 初始化 RedissonClient

在 Spring Boot 项目中,可以通过配置文件或代码初始化 RedissonClient

2.1 配置文件方式

在 application.yml 中配置 Redis 连接:

spring:
  redis:
    host: localhost
    port: 6379
    password: your-password

然后在代码中注入 RedissonClient

    @Resource
    private RedissonClient redisson;
2.2 代码方式(不建议)

直接通过代码初始化 RedissonClient

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

public class RedissonExample {
    public static void main(String[] args) {
        Config config = new Config();
        config.useSingleServer()
              .setAddress("redis://localhost:6379")
              .setPassword("your-password");
        RedissonClient redisson = Redisson.create(config);

        // 使用 redisson 操作 ZSet
    }
}

3. 操作 ZSet

RedissonClient 提供了 RScoredSortedSet 接口来操作 ZSet

3.1 添加元素
  •   有分数

    import org.redisson.api.RScoredSortedSet;
    import org.redisson.api.RedissonClient;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    
    @Component
    public class ZSetService {
    
        @Resource
        private RedissonClient redisson;
    
        /**
         * 添加元素到 ZSet
         *
         * @param key    ZSet 的键
         * @param value  元素值
         * @param score  分数(用于排序)
         */
        public void addToZSet(String key, String value, double score) {
            RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
            zSet.add(score, value);
        }
    }
  • 无分数,使用当前时间戳作为分数

        /**
         * 向 ZSet 中添加元素
         * 使用当前时间戳作为分数
         *
         * @param key   ZSet 的键名
         * @param value 元素的值
         */
        public void addToZSet(String key, String value) {
            // 获取当前时间戳作为分数,时间越新,时间戳越大。
            double score = new Date().getTime();
            RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
            zSet.add(score, value);
        }
3.2 获取元素
  •  获取所有元素

        /**
         * 获取指定键的 ZSet 中的所有元素
         * @param key ZSet 的键名
         * @return 包含 ZSet 所有元素的集合
         */
        public Collection<String> getAllZSetElements(String key) {
            RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
            return zSet.readAll();
        }
  • 按分数范围获取元素

    /**
     * 按分数范围获取元素
     *
     * @param key  ZSet 的键
     * @param minScore 最小分数
     * @param maxScore 最大分数
     * @return 元素集合
     */
    public Collection<String> getElementsByScoreRange(String key, double minScore, double maxScore) {
        RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
        return zSet.valueRange(minScore, true, maxScore, true);
    }
  • 按排名范围获取元素

    /**
     * 按排名范围获取元素
     *
     * @param key  ZSet 的键
     * @param startRank 起始排名(从 0 开始)
     * @param endRank   结束排名
     * @return 元素集合
     */
    public Collection<String> getElementsByRankRange(String key, int startRank, int endRank) {
        RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
        return zSet.valueRange(startRank, endRank);
    }
3.3 删除元素
  • 删除指定元素

    /**
     * 删除指定元素
     *
     * @param key   ZSet 的键
     * @param value 元素值
     * @return 是否删除成功
     */
    public boolean removeElement(String key, String value) {
        RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
        return zSet.remove(value);
    }
  • 按分数范围删除元素

    /**
     * 按分数范围删除元素
     *
     * @param key       ZSet 的键
     * @param minScore  最小分数
     * @param maxScore  最大分数
     * @return 删除的元素数量
     */
    public int removeElementsByScoreRange(String key, double minScore, double maxScore) {
        RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
        return zSet.removeRangeByScore(minScore, true, maxScore, true);
    }
  • 清空元素

    public int removeElementsByScoreRange(String key) {
        RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
        return zSet.clear();
    }
3.4 获取 ZSet 大小
/**
 * 获取 ZSet 的大小
 *
 * @param key ZSet 的键
 * @return ZSet 的大小
 */
public int getZSetSize(String key) {
    RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
    return zSet.size();
}
3.5 获取元素的分数
/**
 * 获取元素的分数
 *
 * @param key   ZSet 的键
 * @param value 元素值
 * @return 元素的分数
 */
public Double getElementScore(String key, String value) {
    RScoredSortedSet<String> zSet = redisson.getScoredSortedSet(key);
    return zSet.getScore(value);
}

总结

通过 RedissonClient,可以轻松实现 ZSet 的存储和操作,包括:

  • 添加元素

  • 按分数或排名范围获取元素

  • 删除元素

  • 获取集合大小

  • 获取元素的分数

Redisson 提供了丰富的 API,支持分布式环境下的高效操作,适合高并发场景。


文章转载自:

http://28V7JCcj.qLpyn.cn
http://QFuDFTFe.qLpyn.cn
http://m7BZtpLA.qLpyn.cn
http://TzEhk2Ci.qLpyn.cn
http://EgT0QmOl.qLpyn.cn
http://YPsW4VCt.qLpyn.cn
http://wJ7jxxSr.qLpyn.cn
http://dnr9rAJs.qLpyn.cn
http://7gK7FzSl.qLpyn.cn
http://AqZRWw1v.qLpyn.cn
http://wy3R5fun.qLpyn.cn
http://nGwY7ZcK.qLpyn.cn
http://Zip4So2f.qLpyn.cn
http://OwkvsNPX.qLpyn.cn
http://XjPqDG99.qLpyn.cn
http://2pm7e8uM.qLpyn.cn
http://2p3L60OI.qLpyn.cn
http://TJo2Q5wZ.qLpyn.cn
http://TZUwSNgB.qLpyn.cn
http://XZP2rEw6.qLpyn.cn
http://npHVtH0G.qLpyn.cn
http://lJXIKEKO.qLpyn.cn
http://3wPvLFfQ.qLpyn.cn
http://f1QTGcMj.qLpyn.cn
http://Fg19nMUg.qLpyn.cn
http://N2T8XOzb.qLpyn.cn
http://2Q8FJLXS.qLpyn.cn
http://RIIVsRl0.qLpyn.cn
http://ECIiJgbC.qLpyn.cn
http://64AMBqxk.qLpyn.cn
http://www.dtcms.com/a/28559.html

相关文章:

  • 九、OSG学习笔记-NodeVisitor节点遍历器
  • 当滑动组件连续触发回调函数的三种解决办法
  • 回调处理器
  • Qt程序退出相关资源释放问题
  • MySQL基础回顾#1
  • jQuery UI CSS 框架 API
  • PyTorch 系统教程:PyTorch 入门项目(简单线性回归)
  • 使用代码与 AnythingLLM 交互的基本方法和示例
  • 30天开发操作系统 第22天 -- 用C语言编写应用程序
  • 模型训练与优化遇到的问题3:安装STM32Cube.AI
  • Webpack的持久化缓存机制具体是如何实现的?
  • 【鸿蒙笔记-基础篇_状态管理】
  • scrapy pipelines过滤重复数据
  • Nginx WebSocket 长连接及数据容量配置
  • 文献阅读 250220-Convective potential and fuel availability complement near-surface
  • 10个Python 语法错误(SyntaxError)常见例子及解决方案
  • 2016年下半年软件设计师上午题的知识点总结(附真题及答案解析)
  • 后端Java Stream数据流的使用=>代替for循环
  • 接口测试-API测试中常用的协议(中)
  • 解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
  • 本地在ollama上部署deepseek或llama大模型
  • 2024华为OD机试真题-恢复数字序列(C++/Java/Python)-E卷-100分
  • Vue 中组件通信的方式有哪些,如何实现父子组件和非父子组件之间的通信?
  • 【含文档+PPT+源码】基于大数据的交通流量预测系统
  • 解决本地模拟IP的DHCP冲突问题
  • NutUI内网离线部署
  • 20250218反函数求导
  • IPv6报头40字节具体怎么分配的?
  • 快速入门Springboot+vue——MybatisPlus快速上手
  • 16 中介者(Mediator)模式