热榜 ZSET 的加分需要同一次用户意图最多生效一次。现有包装层只有 GetBytes/SetBytes/Del/DelByPattern/MGet,缺仅当不存在时写入, 调用方只能先 GET 再 SET,两次往返之间必然存在并发窗口。 SetNX 是唯一需要新增的 Redis 原语: - key 由调用方用 c.Key(...) 拼好,前缀时机与其他原语保持一致; - nil client 与 Redis 故障都返回 error 而不是 (false, nil)——把故障 说成已生效会让该次加分被永久跳过,与宁可少加也不多加的取舍 不同:那是崩溃窗口,这是本可重试的失败。 测试钉住两个性质:只有第一次拿到占位;后到的调用不覆盖值、不刷新 TTL(否则反复重投会让占位永不过期)。
62 lines
1.9 KiB
Go
62 lines
1.9 KiB
Go
package redis
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"time"
|
||
)
|
||
|
||
func (c *Client) GetBytes(ctx context.Context, key string) ([]byte, error) {
|
||
if c == nil || c.rdb == nil {
|
||
return nil, errors.New("redis client not initialized")
|
||
}
|
||
return c.rdb.Get(ctx, key).Bytes()
|
||
}
|
||
|
||
func (c *Client) SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||
if c == nil || c.rdb == nil {
|
||
return errors.New("redis client not initialized")
|
||
}
|
||
return c.rdb.Set(ctx, key, value, ttl).Err()
|
||
}
|
||
|
||
func (c *Client) Del(ctx context.Context, key string) error {
|
||
if c == nil || c.rdb == nil {
|
||
return errors.New("redis client not initialized")
|
||
}
|
||
return c.rdb.Del(ctx, key).Err()
|
||
}
|
||
|
||
// SetNX 仅在 key 不存在时写入,返回是否抢到了这个键。
|
||
//
|
||
// key 由调用方用 c.Key(...) 拼好(本方法不加前缀)——加前缀的时机必须
|
||
// 和其他原语一致,否则同一个逻辑键会因为调用路径不同变成两个物理键。
|
||
//
|
||
// 失败(含 nil client)必须返回 error 而不是 (false, nil):调用方用它
|
||
// 判断"这次意图是否已经生效过",把 Redis 故障静默说成"已生效"会导致
|
||
// 该次加分被永久跳过。
|
||
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
|
||
if c == nil || c.rdb == nil {
|
||
return false, errors.New("redis client not initialized")
|
||
}
|
||
return c.rdb.SetNX(ctx, key, value, ttl).Result()
|
||
}
|
||
|
||
func (c *Client) DelByPattern(ctx context.Context, pattern string) error {
|
||
if c == nil || c.rdb == nil {
|
||
return nil
|
||
}
|
||
iter := c.rdb.Scan(ctx, 0, pattern, 0).Iterator()
|
||
for iter.Next(ctx) {
|
||
_ = c.rdb.Del(ctx, iter.Val())
|
||
}
|
||
return iter.Err()
|
||
}
|
||
|
||
func (c *Client) MGet(cacheCtx context.Context, cacheKeys ...string) ([]interface{}, error) {
|
||
if c == nil || c.rdb == nil {
|
||
return nil, errors.New("redis client not initialized")
|
||
}
|
||
return c.rdb.MGet(cacheCtx, cacheKeys...).Result()
|
||
}
|