Set 设置帖子缓存,使用随机过期时间防止缓存雪崩
(ctx context.Context, key string, post domain.Post)
| 84 | |
| 85 | // Set 设置帖子缓存,使用随机过期时间防止缓存雪崩 |
| 86 | func (c *postCache) Set(ctx context.Context, key string, post domain.Post) error { |
| 87 | if key == "" { |
| 88 | return fmt.Errorf("无效的帖子ID: %s", key) |
| 89 | } |
| 90 | |
| 91 | data, err := json.Marshal(post) |
| 92 | if err != nil { |
| 93 | return fmt.Errorf("序列化帖子数据失败: %v", err) |
| 94 | } |
| 95 | |
| 96 | // 在基础过期时间上增加随机时间,范围是0-5分钟 |
| 97 | randomExpiration := c.expiration + time.Duration(rand.Int63n(300))*time.Second |
| 98 | err = c.client.Set(ctx, c.key(key), data, randomExpiration).Err() |
| 99 | if err != nil { |
| 100 | return fmt.Errorf("设置缓存失败: %v", err) |
| 101 | } |
| 102 | |
| 103 | // 删除空对象标记(如果存在) |
| 104 | _ = c.client.Del(ctx, c.emptyKey(key)) |
| 105 | |
| 106 | return nil |
| 107 | } |
| 108 | |
| 109 | // SetEmpty 缓存空对象,使用较短的过期时间 |
| 110 | func (c *postCache) SetEmpty(ctx context.Context, key string) error { |