/
redis.go
98 lines (81 loc) · 2.19 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package redis
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
"github.com/emadghaffari/virgool/blog/conf"
)
var (
// Database var
Database Redis = &rd{}
// sync
once sync.Once
// error
err error
)
// Redis interface
type Redis interface {
Connect(config *conf.GlobalConfiguration) error
GetDatabase() *redis.Client
Get(ctx context.Context, key string, dest interface{}) error
Set(ctx context.Context, key string, value interface{}, duration time.Duration) error
Del(ctx context.Context, key ...string) error
}
type rd struct {
db *redis.Client
}
func (s *rd) Connect(config *conf.GlobalConfiguration) error {
once.Do(func() {
s.db = redis.NewClient(&redis.Options{
DB: config.Redis.DB,
Addr: config.Redis.Host,
Username: config.Redis.Username,
Password: config.Redis.Password,
})
if err = s.db.Ping(context.Background()).Err(); err != nil {
logrus.WithFields(logrus.Fields{
"error": fmt.Sprintf("Config redis database Error: %s", err),
}).Fatal(fmt.Sprintf("Config redis database Error: %s", err))
}
})
return err
}
func (s *rd) GetDatabase() *redis.Client {
return s.db
}
// Set meth a new key,value
func (s *rd) Set(ctx context.Context, key string, value interface{}, duration time.Duration) error {
p, err := json.Marshal(value)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": fmt.Sprintf("Marshal Error for Set New item in Redis: %s", err),
}).Fatal(fmt.Sprintf("Marshal Error for Set New item in Redis: %s", err))
return err
}
return s.db.Set(ctx, key, p, duration).Err()
}
// Get meth, get value with key
func (s *rd) Get(ctx context.Context, key string, dest interface{}) error {
p, err := s.db.Get(ctx, key).Result()
if p == "" {
return fmt.Errorf("Value Not Found")
}
if err != nil {
logrus.WithFields(logrus.Fields{
"error": fmt.Sprintf("Error in Get value from Redis: %s", err),
}).Fatal(fmt.Sprintf("Error in Get value from Redis: %s", err))
return err
}
return json.Unmarshal([]byte(p), &dest)
}
func (s *rd) Del(ctx context.Context, key ...string) error {
_, err := s.db.Del(ctx, key...).Result()
if err != nil {
return err
}
return nil
}