-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
57 lines (46 loc) · 1.21 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cache
import (
"context"
"encoding/json"
"fmt"
"time"
redis "github.com/redis/go-redis/v9"
)
// RedisCacheRepository redis cache service
type RedisCacheRepository struct {
client *redis.Client
}
// NewRedisCacheRepository new redis cache service
func NewRedisCacheRepository(client *redis.Client) *RedisCacheRepository {
return &RedisCacheRepository{
client,
}
}
// Set set cache based on given key
func (redisCache *RedisCacheRepository) Set(key string, value interface{}, expiration time.Duration) error {
byteValue, err := json.Marshal(value)
if err != nil {
return err
}
strValue := string(byteValue)
return redisCache.client.Set(context.TODO(), key, strValue, expiration).Err()
}
// Get get cache base on given key
func (redisCache *RedisCacheRepository) Get(key string, data interface{}) (err error) {
result, err := redisCache.client.Get(context.TODO(), key).Result()
if err != nil {
return nil
}
value := fmt.Sprintf("%v", result)
if value != "" {
err = json.Unmarshal([]byte(value), &data)
if err != nil {
return err
}
}
return nil
}
// Delete cache base on given key
func (redisCache *RedisCacheRepository) Delete(key string) {
redisCache.client.Expire(context.TODO(), key, 0)
}