/
redis.go
71 lines (55 loc) · 1.28 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
package database
import (
"context"
"errors"
"fmt"
"github.com/makeok/go-web-init/pkg/config"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
)
var (
RedisDisableError = errors.New("redis disable")
)
type RedisDB struct {
enable bool
*redis.Client
}
func NewRedisClient(conf *config.RedisConfig) (*RedisDB, error) {
if !conf.Enable {
logrus.Info("redis disable")
return &RedisDB{}, nil
}
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", conf.Host, conf.Port),
Password: conf.Password,
DB: 0,
})
if _, err := rdb.Ping(context.Background()).Result(); err != nil {
return nil, err
}
return &RedisDB{
enable: true,
Client: rdb,
}, nil
}
func (rdb *RedisDB) Endable() bool {
return rdb.enable
}
func (rdb *RedisDB) HGet(key, field string, obj interface{}) error {
if !rdb.enable {
return RedisDisableError
}
return rdb.Client.HGet(context.Background(), key, field).Scan(obj)
}
func (rdb *RedisDB) HSet(key, field string, val interface{}) error {
if !rdb.enable {
return nil
}
return rdb.Client.HSet(context.Background(), key, field, val).Err()
}
func (rdb *RedisDB) HDel(key string, fields ...string) error {
if !rdb.enable {
return nil
}
return rdb.Client.HDel(context.Background(), key, fields...).Err()
}