*Redis ZINCRBY 命令
对 Sorted Set 中指定 member 的 score 做增量添加。
*语法
ZINCRBY key increment member
*参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| key | String | 是 | Sorted Set 的键名 |
| increment | Double | 是 | 增量值,可为负数(递减) |
| member | String | 是 | 成员名 |
*返回值
| 条件 | 返回值 |
|---|---|
| 递增成功 | 返回新的 score(String) |
| member 不存在 | 先以 score=0 创建,再递增 |
*时间复杂度
O(log(N)),N 为 Sorted Set 成员数量。
*示例
> ZADD leaderboard 100 "player1"
(integer) 1
> ZINCRBY leaderboard 50 "player1"
"150"
> ZINCRBY leaderboard -30 "player1"
"120"
# member 不存在
> ZINCRBY leaderboard 100 "player2"
"100"
*常见错误
- increment 非数字:返回错误。
*最佳实践
- 实时排行榜:点赞、积分等场景用 ZINCRBY 实时更新分数,ZRANGE/ZREVRANGE 查询排名。
- 限流计数:score 为时间窗口内的请求数,过期后清理。
- 原子递增:ZINCRBY 是原子操作,并发安全。
*FAQ
Q: ZINCRBY 和 INCR 有什么区别? A: INCR 操作 String(O(1),整数);ZINCRBY 操作 Sorted Set 的 score(O(log(N)),浮点数)。
Q: score 可以为负数吗? A: 可以。ZINCRBY 增量为负就是递减。