Redis 有序集合(sorted set)
ZSet 按分数排序,做排行榜、延迟队列、范围查询。
Key Points每个成员带一个 score,自动按分数排序且去重;排行榜的标配。
排行榜
Shell
ZADD rank 95 "alice" 88 "bob" 76 "carol"
ZREVRANGE rank 0 2 WITHSCORES # 前 3 名(分数降序)
ZRANK rank "bob" # bob 的升序排名(从 0)
ZINCRBY rank 5 "alice" # alice 分数 +5Output
1) "alice"
2) "95"
3) "bob"
4) "88"
5) "carol"
6) "76"
(integer) 1范围与延迟队列
Shell
ZRANGEBYSCORE rank 80 100 # 分数在 [80,100] 的成员
# 延迟队列:score 设为执行时间戳,取到期任务
ZADD delayq 1717000000 "job:1"
ZRANGEBYSCORE delayq 0 1716999999 WITHSCORESA ZSet deduplicates by member (re-ZADD updates the score). For live leaderboards combine
ZREVRANGE (top N), ZSCORE (personal) and ZRANK (rank).排行榜
Shell
ZADD rank 95 "alice" 88 "bob" 76 "carol"
ZREVRANGE rank 0 2 WITHSCORES # 前 3 名(分数降序)
ZRANK rank "bob" # bob 的升序排名(从 0)
ZINCRBY rank 5 "alice" # alice 分数 +5Output
1) "alice"
2) "95"
3) "bob"
4) "88"
5) "carol"
6) "76"
(integer) 1范围与延迟队列
Shell
ZRANGEBYSCORE rank 80 100 # 分数在 [80,100] 的成员
# 延迟队列:score 设为执行时间戳,取到期任务
ZADD delayq 1717000000 "job:1"
ZRANGEBYSCORE delayq 0 1716999999 WITHSCORESZSet 按
member 去重(同 member 再 ZADD 会更新分数)。做实时排行榜时,ZREVRANGE 取前 N + ZSCORE 取个人分数 + ZRANK 取名次,三者配合即可。