Skip to content

Commit bdd0d4e

Browse files
committed
feat(ecache): using redis as a cache implementation
1 parent 75a5d73 commit bdd0d4e

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

ecache/redis/redis_cache.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package redis
2+
3+
import (
4+
"context"
5+
"time"
6+
7+
"github.com/pkg/errors"
8+
"github.com/redis/go-redis/v9"
9+
)
10+
11+
type cache struct {
12+
rdb *redis.Client
13+
}
14+
15+
func NewCache(client *redis.Client) *cache {
16+
return &cache{
17+
rdb: client,
18+
}
19+
}
20+
21+
func (c *cache) Del(ctx context.Context, keys ...string) (affected int64, err error) {
22+
if affected, err = c.rdb.Del(ctx, keys...).Result(); err != nil {
23+
return affected, errors.WithStack(err)
24+
}
25+
return affected, nil
26+
}
27+
28+
func (c *cache) Get(ctx context.Context, key string) (val []byte, err error) {
29+
if val, err = c.rdb.Get(ctx, key).Bytes(); err != nil {
30+
return nil, errors.WithStack(err)
31+
}
32+
return val, nil
33+
}
34+
35+
func (c *cache) GetAsUint64(ctx context.Context, key string) (val uint64, err error) {
36+
if val, err = c.rdb.Get(ctx, key).Uint64(); err != nil {
37+
return 0, errors.WithStack(err)
38+
}
39+
return val, nil
40+
}
41+
42+
func (c *cache) Set(ctx context.Context, key string, val []byte, expire time.Duration) (err error) {
43+
if err = c.rdb.Set(ctx, key, val, expire).Err(); err != nil {
44+
return errors.WithStack(err)
45+
}
46+
return nil
47+
}
48+
49+
func (c *cache) IsKeyNotFound(err error) bool {
50+
return errors.Is(err, redis.Nil)
51+
}

0 commit comments

Comments
 (0)