| 40 | } |
| 41 | |
| 42 | func (r *rankingCache) Set(ctx context.Context, posts []domain.Post) error { |
| 43 | // 预处理帖子内容 |
| 44 | for i := range posts { |
| 45 | posts[i].Content = posts[i].Abstract() |
| 46 | } |
| 47 | |
| 48 | // 序列化帖子数据 |
| 49 | val, err := json.Marshal(posts) |
| 50 | if err != nil { |
| 51 | r.logger.Error("序列化帖子失败", zap.Error(err)) |
| 52 | return ErrMarshalPost |
| 53 | } |
| 54 | |
| 55 | // 设置缓存 |
| 56 | if err := r.client.Set(ctx, r.key, val, r.expiration).Err(); err != nil { |
| 57 | r.logger.Error("设置缓存失败", |
| 58 | zap.String("key", r.key), |
| 59 | zap.Error(err)) |
| 60 | return ErrSetCache |
| 61 | } |
| 62 | |
| 63 | r.logger.Info("缓存设置成功", |
| 64 | zap.String("key", r.key), |
| 65 | zap.Int("post_count", len(posts))) |
| 66 | return nil |
| 67 | } |
| 68 | |
| 69 | func (r *rankingCache) Get(ctx context.Context) ([]domain.Post, error) { |
| 70 | // 获取缓存数据 |