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

注明原文https://zhangxiaofan.blog.csdn.net/article/details/129625822


目录

前言

Redisson依赖

Redisson配置

Redisson ZSet工具类(基础操作)

总结


前言

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

Redisson依赖

Spring工程引入 redisson

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

这里使用版本是:

      <dependency>
            <groupId>org.redisson</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 = "spring.redis")
public class RedissonConfig {

    private String host;

    private String port;

    private String password;

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

Redisson ZSet工具类(基础操作

package redisson.utis;

import org.redisson.api.RBatch;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.redisson.client.protocol.ScoredEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@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 = client.getScoredSortedSet(key);
        if (null != refreshExpire) {
            scoredSortedSet.expire(Duration.ofSeconds(DEFAULT_EXPIRE_TIME_SECONDS));
        }
        scoredSortedSet.addAsync(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 = client.getScoredSortedSet(key);
        // 只能针对 key 设置过期时间,zset 中的元素不能单独设置.
        scoredSortedSet.add(0, DEFAULT_SCORE_KEY);
        scoredSortedSet.expire(Duration.ofSeconds(seconds));
        RBatch batch = client.createBatch();
        map.forEach((member, score) -> {
            batch.getScoredSortedSet(key).addAsync(score, member);
        });
        batch.execute();
    }

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

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

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


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

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


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

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


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


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


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

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


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

总结

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

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

原文地址:https://blog.csdn.net/q258523454/article/details/129625822

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_37768.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注