// zset存
// 初始化key,value为userId,分数为0
redisTemplate.opsForZSet().add(key, userId, 0 ) ;
// 设置过期时间
redisTemplate.expire(key, Duration.ofDays(2));
// 给key,value为userId,原子增score的分数
redisTemplate.opsForZSet().incrementScore(key, userId, score);
// zset取
// 查询top5的从小到大 zrange key 0 4
Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
if(set==null || set.isEmpty()){
throw new Exception("key中暂无数据");
}
// userId移除
stringRedisTemplate.opsForZSet().remove(key, userId);
// 滚动分页查询
// ZREVRANGEBYSCORE key Max Min LIMIT offset count
// Max:当前最大分数(第一次查询使用) | 上一次查询的最小分数 (除了第一次查询之外都使用)
// Min:0
// offset:0 (第一次查询使用) | 在上一次的结果中,与最小值一样的元素个数 (除了第一次查询之外都使用)
// count:分页大小 比如3
Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
.reverseRangeByScoreWithScores(key, 0, max, offset, 3);
// 非空判断
if (typedTuples == null || typedTuples.isEmpty()) {
return Result.ok();
}
// 解析数据:userId、minScore、offset
List<Long> ids = new ArrayList<>(typedTuples.size());
long minScore = 0; // 2
int os = 1; // 2
for (ZSetOperations.TypedTuple<String> tuple : typedTuples) { // 5 4 4 2 2
// 4.1.获取userId
ids.add(Long.valueOf(tuple.getValue()));
// 4.2.获取分数
long score = tuple.getScore().longValue();
if (score == minScore) {
os++;
} else {
minScore = score;
os = 1;
}
}
// 将minScore即为max和os即为offset返回给前端
Redis:ZSet数据结构使用
于 2023-03-27 07:31:14 首次发布