Redis 有序集合(sorted set)

ZSet 按分数排序,做排行榜、延迟队列、范围查询。

Beginner
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 分数 +5
Output
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 WITHSCORES
A ZSet deduplicates by member (re-ZADD updates the score). For live leaderboards combine ZREVRANGE (top N), ZSCORE (personal) and ZRANK (rank).

Friends & Partners