|
| 1 | +package redis |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/redis/go-redis/v9" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +type Codec interface { |
| 10 | + Marshal(value any) ([]byte, error) |
| 11 | + Unmarshal(data []byte, value any) error |
| 12 | +} |
| 13 | + |
| 14 | +type Cache[T any] struct { |
| 15 | + cache *ByteCache |
| 16 | + codec Codec |
| 17 | +} |
| 18 | + |
| 19 | +func NewCache[T any](client *redis.Client, codec Codec) *Cache[T] { |
| 20 | + return &Cache[T]{ |
| 21 | + cache: NewByteCache(client), |
| 22 | + codec: codec, |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func (m *Cache[T]) Set(ctx context.Context, key string, val T, expiration time.Duration) error { |
| 27 | + raw, err := m.codec.Marshal(val) |
| 28 | + if err != nil { |
| 29 | + return err |
| 30 | + } |
| 31 | + return m.cache.Set(ctx, key, raw, expiration) |
| 32 | +} |
| 33 | + |
| 34 | +func (m *Cache[T]) Get(ctx context.Context, key string) (*T, error) { |
| 35 | + raw, err := m.cache.Get(ctx, key) |
| 36 | + if err != nil { |
| 37 | + return nil, err |
| 38 | + } |
| 39 | + if raw == nil { |
| 40 | + return nil, nil |
| 41 | + } |
| 42 | + var val T |
| 43 | + err = m.codec.Unmarshal(*raw, &val) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + return &val, nil |
| 48 | +} |
| 49 | + |
| 50 | +func (m *Cache[T]) Del(ctx context.Context, key string) error { |
| 51 | + return m.cache.Del(ctx, key) |
| 52 | +} |
| 53 | + |
| 54 | +func (m *Cache[T]) MultiSet(ctx context.Context, valMap map[string]T, expiration time.Duration) error { |
| 55 | + for k, v := range valMap { |
| 56 | + err := m.Set(ctx, k, v, expiration) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + } |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +func (m *Cache[T]) MultiGet(ctx context.Context, keys []string) (map[string]T, error) { |
| 65 | + result := make(map[string]T) |
| 66 | + for _, key := range keys { |
| 67 | + val, err := m.Get(ctx, key) |
| 68 | + if err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + if val != nil { |
| 72 | + result[key] = *val |
| 73 | + } |
| 74 | + } |
| 75 | + return result, nil |
| 76 | +} |
| 77 | + |
| 78 | +func (m *Cache[T]) MultiDel(ctx context.Context, keys []string) error { |
| 79 | + for _, key := range keys { |
| 80 | + err := m.Del(ctx, key) |
| 81 | + if err != nil { |
| 82 | + return err |
| 83 | + } |
| 84 | + } |
| 85 | + return nil |
| 86 | +} |
| 87 | + |
| 88 | +func (m *Cache[T]) DelAll(ctx context.Context) error { |
| 89 | + return m.cache.DelAll(ctx) |
| 90 | +} |
| 91 | + |
| 92 | +func (m *Cache[T]) Close() error { |
| 93 | + return nil |
| 94 | +} |
0 commit comments