Spring使用Redisson工具类操作ZSet集合(基础操作汇总)

时间:2025-03-22 07:57:15

手打不易,如果转摘,请注明出处!

注明原文:/article/details/129625822


目录

前言

Redisson依赖

Redisson配置

Redisson ZSet工具类(基础操作)

总结


前言

Redisson其他工具类,像 String、Hash、Set 网上都有比较全的方法了,这里只列举 ZSet 数据类型的基本操作。

Redisson依赖

Spring工程先引入 redisson:

      <dependency>
            <groupId></groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version></version>
        </dependency>

我这里使用的版本是:

      <dependency>
            <groupId></groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.17.1</version>
        </dependency>

Redisson配置

yaml配置,我这里用的本地单节点测试

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456

RedissonClient Bean创建

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "")
public class RedissonConfig {

    private String host;

    private String port;

    private String password;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() {
        // 1、创建配置
        Config config = new Config();
        (new JsonJacksonCodec())
                .useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setPassword(password);
        return (config);
    }
}

Redisson ZSet工具类(基础操作)

package ;

import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;

@Component
public class RedissonZSetService {

    @Autowired
    private RedissonClient client;

    public static final String DEFAULT_SCORE_KEY = "default";

    /**
     * 默认保存时间
     */
    private static final long DEFAULT_EXPIRE_TIME_SECONDS = 3600L;

    /**
     * 新增ZSet元素,存在则刷新
     *
     * @param refreshExpire 过期时间,不为null则重新赋值
     */
    public <T> void zscoreAddAsync(String key, double score, T member, Long refreshExpire) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (null != refreshExpire) {
            ((DEFAULT_EXPIRE_TIME_SECONDS));
        }
        (score, member);
    }

    /**
     * 批量新增
     */
    public <T> void zScoreAddAsyncBatch(String key, Map<String, Double> map, long seconds) {
        if (seconds <= 0) {
            seconds = DEFAULT_EXPIRE_TIME_SECONDS;
        }
        RScoredSortedSet<Object> scoredSortedSet = (key);
        // 只能针对 key 设置过期时间,zset 中的元素不能单独设置.
        (0, DEFAULT_SCORE_KEY);
        ((seconds));
        RBatch batch = ();
        ((member, score) -> {
            (key).addAsync(score, member);
        });
        ();
    }

    /**
     * 读取指定 key 下所有 member, 按照 score 升序(默认)
     */
    public Collection<Object> getZSetMembers(String key, int startIndex, int endIndex) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        return (startIndex, endIndex);
    }

    /**
     * 取指定 key 下所有 member, 按照 score 降序
     */
    public Collection<Object> getZSetMembersReversed(String key, int startIndex, int endIndex) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        return (startIndex, endIndex);
    }

    /**
     * 读取 member和score, 按照 score 升序(默认)
     */
    public Collection<ScoredEntry<Object>> getZSetEntryRange(String key, int startIndex, int endIndex) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        return (startIndex, endIndex);
    }


    /**
     * 读取 member和score, 按照 score 降序
     */
    public Collection<ScoredEntry<Object>> getZSetEntryRangeReversed(String key, int startIndex, int endIndex) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        return (startIndex, endIndex);
    }

    /**
     * 读取指定 key 下 member 的 score
     * 返回null 表示不存在
     */
    public Double getZSetMemberScore(String key, String member) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return null;
        }
        return (member);
    }


    /**
     * 读取指定 key 下 memberList 的 score
     * 返回null 表示不存在
     */
    public Double getZSetMemberScore(String key, List<String> memberList) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return null;
        }
        return (memberList);
    }

    /**
     * 读取指定 key 下 member 的 rank 排名(升序情况)
     * 返回null 表示不存在, 下标从0开始
     */
    public Integer getZSetMemberRank(String key, String member) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return null;
        }
        return (member);
    }


    /**
     * 异步删除指定 ZSet 中的指定 memberName 元素
     */
    public void removeZSetMemberAsync(String key, String memberName) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return;
        }
        (memberName);
    }


    /**
     * 异步批量删除指定 ZSet 中的指定 member 元素列表
     */
    public void removeZSetMemberAsync(String key, List<String> memberList) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return;
        }
        RBatch batch = ();
        (member -> (key).removeAsync(member));
        ();
    }


    /**
     * 统计ZSet分数范围内元素总数. 区间包含分数本身
     * 注意这里不能用 -1 代替最大值
     */
    public int getZSetCountByScoresInclusive(String key, double startScore, double endScore) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return 0;
        }
        return (startScore, true, endScore, true);
    }

    /**
     * 返回ZSet分数范围内 member 列表. 区间包含分数本身.
     * 注意这里不能用 -1 代替最大值
     */
    public Collection<Object> getZSetMembersByScoresInclusive(String key, double startScore, double endScore) {
        RScoredSortedSet<Object> scoredSortedSet = (key);
        if (!()) {
            return null;
        }
        return (startScore, true, endScore, true);
    }


    /**
     * 获取所有的指定前缀 keys
     */
    public Set<String> getKeys(String prefix) {
        Iterable<String> keysByPattern = ().getKeysByPattern(prefix);
        Set<String> keys = new HashSet<>();
        for (String s : keysByPattern) {
            (s);
        }
        return keys;
    }
}

总结

是不能针对每个元素(member)做过期设置的,只能对整个key做过期时间设置。

针对带权重的排名、计分相关的操作,具有独特优势。