SetPubList 设置已发布帖子列表缓存
(ctx context.Context, page int, size int, posts []domain.Post)
| 296 | |
| 297 | // SetPubList 设置已发布帖子列表缓存 |
| 298 | func (c *postCache) SetPubList(ctx context.Context, page int, size int, posts []domain.Post) error { |
| 299 | if page <= 0 || size <= 0 { |
| 300 | return fmt.Errorf("无效的分页参数: page=%d, size=%d", page, size) |
| 301 | } |
| 302 | |
| 303 | // 获取分布式锁 |
| 304 | key := fmt.Sprintf("%d_%d", page, size) |
| 305 | lockKey := c.lockKey("publist:" + key) |
| 306 | success, err := c.acquireLock(ctx, lockKey, 5*time.Second) |
| 307 | if err != nil { |
| 308 | return fmt.Errorf("获取分布式锁失败: %v", err) |
| 309 | } |
| 310 | if !success { |
| 311 | return fmt.Errorf("获取分布式锁失败: 锁已被占用") |
| 312 | } |
| 313 | defer c.releaseLock(ctx, lockKey) |
| 314 | |
| 315 | data, err := json.Marshal(posts) |
| 316 | if err != nil { |
| 317 | return fmt.Errorf("序列化已发布帖子列表数据失败: %v", err) |
| 318 | } |
| 319 | |
| 320 | // 列表缓存使用随机过期时间 |
| 321 | randomExpiration := c.expiration + time.Duration(rand.Int63n(300))*time.Second |
| 322 | return c.client.Set(ctx, c.pubListKey(key), data, randomExpiration).Err() |
| 323 | } |
| 324 | |
| 325 | // DelPubList 删除已发布帖子列表缓存 |
| 326 | func (c *postCache) DelPubList(ctx context.Context, key string) error { |
nothing calls this directly
no test coverage detected