SetPub 设置已发布帖子缓存
(ctx context.Context, key string, post domain.Post)
| 401 | |
| 402 | // SetPub 设置已发布帖子缓存 |
| 403 | func (c *postCache) SetPub(ctx context.Context, key string, post domain.Post) error { |
| 404 | if key == "" { |
| 405 | return fmt.Errorf("无效的帖子ID: %s", key) |
| 406 | } |
| 407 | |
| 408 | // 获取分布式锁 |
| 409 | lockKey := c.lockKey("pub:" + key) |
| 410 | success, err := c.acquireLock(ctx, lockKey, 5*time.Second) |
| 411 | if err != nil { |
| 412 | return fmt.Errorf("获取分布式锁失败: %v", err) |
| 413 | } |
| 414 | if !success { |
| 415 | return fmt.Errorf("获取分布式锁失败: 锁已被占用") |
| 416 | } |
| 417 | defer c.releaseLock(ctx, lockKey) |
| 418 | |
| 419 | data, err := json.Marshal(post) |
| 420 | if err != nil { |
| 421 | return fmt.Errorf("序列化已发布帖子数据失败: %v", err) |
| 422 | } |
| 423 | |
| 424 | // 使用随机过期时间 |
| 425 | randomExpiration := c.expiration + time.Duration(rand.Int63n(300))*time.Second |
| 426 | err = c.client.Set(ctx, c.pubKey(key), data, randomExpiration).Err() |
| 427 | if err != nil { |
| 428 | return fmt.Errorf("设置缓存失败: %v", err) |
| 429 | } |
| 430 | |
| 431 | // 删除空对象标记(如果存在) |
| 432 | _ = c.client.Del(ctx, c.emptyKey(key)) |
| 433 | |
| 434 | return nil |
| 435 | } |
| 436 | |
| 437 | // DelPub 删除已发布帖子缓存 |
| 438 | func (c *postCache) DelPub(ctx context.Context, key string) error { |
nothing calls this directly
no test coverage detected