|
| 1 | +package memory |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "strconv" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/alicebob/miniredis/v2" |
| 9 | + "github.com/pkg/errors" |
| 10 | +) |
| 11 | + |
| 12 | +type cache struct { |
| 13 | + rdb *miniredis.Miniredis |
| 14 | +} |
| 15 | + |
| 16 | +func NewCache() (*cache, error) { |
| 17 | + rdb, err := miniredis.Run() |
| 18 | + if err != nil { |
| 19 | + return nil, errors.WithStack(err) |
| 20 | + } |
| 21 | + return &cache{ |
| 22 | + rdb: rdb, |
| 23 | + }, nil |
| 24 | +} |
| 25 | + |
| 26 | +func (c *cache) Del(ctx context.Context, keys ...string) (affected int64, err error) { |
| 27 | + for _, key := range keys { |
| 28 | + if c.rdb.Del(key) { |
| 29 | + affected++ |
| 30 | + } |
| 31 | + } |
| 32 | + return affected, nil |
| 33 | +} |
| 34 | + |
| 35 | +func (c *cache) Get(ctx context.Context, key string) (val []byte, err error) { |
| 36 | + data, err := c.rdb.Get(key) |
| 37 | + if err != nil { |
| 38 | + return nil, errors.WithStack(err) |
| 39 | + } |
| 40 | + return []byte(data), nil |
| 41 | +} |
| 42 | + |
| 43 | +func (c *cache) GetAsUint64(ctx context.Context, key string) (val uint64, err error) { |
| 44 | + data, err := c.rdb.Get(key) |
| 45 | + if err != nil { |
| 46 | + return 0, errors.WithStack(err) |
| 47 | + } |
| 48 | + return strconv.ParseUint(data, 10, 64) |
| 49 | +} |
| 50 | +func (c *cache) Set(ctx context.Context, key string, val []byte, expire time.Duration) (err error) { |
| 51 | + if err = c.rdb.Set(key, string(val)); err != nil { |
| 52 | + return errors.WithStack(err) |
| 53 | + } |
| 54 | + c.rdb.SetTTL(key, expire) |
| 55 | + return nil |
| 56 | +} |
| 57 | +func (c *cache) IsKeyNotFound(err error) bool { |
| 58 | + return errors.Is(err, miniredis.ErrKeyNotFound) |
| 59 | +} |
0 commit comments