CacheData 序列化数据并存储到 Redis 和布隆过滤器中
(cb *CacheBloom, ctx context.Context, key string, data T, ttl time.Duration)
| 69 | |
| 70 | // CacheData 序列化数据并存储到 Redis 和布隆过滤器中 |
| 71 | func CacheData[T any](cb *CacheBloom, ctx context.Context, key string, data T, ttl time.Duration) (T, error) { |
| 72 | if key == "" { |
| 73 | return data, errors.New("键不能为空") |
| 74 | } |
| 75 | |
| 76 | if ttl <= 0 { |
| 77 | return data, errors.New("过期时间必须为正数") |
| 78 | } |
| 79 | |
| 80 | serializedData, err := json.Marshal(data) |
| 81 | if err != nil { |
| 82 | return data, err |
| 83 | } |
| 84 | |
| 85 | // 使用pipeline优化Redis操作 |
| 86 | pipe := cb.client.Pipeline() |
| 87 | pipe.Set(ctx, key, serializedData, ttl) |
| 88 | _, err = pipe.Exec(ctx) |
| 89 | if err != nil { |
| 90 | return data, err |
| 91 | } |
| 92 | |
| 93 | cb.bf.AddString(key) |
| 94 | return data, nil |
| 95 | } |
| 96 | |
| 97 | // SetEmptyCache 缓存空对象,防止缓存穿透 |
| 98 | func (cb *CacheBloom) SetEmptyCache(ctx context.Context, key string, ttl time.Duration) error { |