/
Redis.go
executable file
·78 lines (72 loc) · 1.66 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
package library
/**
@auth CrastGin
@date 2020-10
*/
import (
"fmt"
"github.com/go-redis/redis"
"strconv"
"sync"
"time"
)
type Redis struct {
*redis.Client
}
var (
redisInstance []*Redis
redisOnce []sync.Once
)
// get singleton redis
func RedisInstance(selectDb ...int) *Redis {
db := 16
if len(selectDb) > 0 && selectDb[0] >= 0 {
db = selectDb[0]
}
if redisOnce == nil {
redisOnce = make([]sync.Once, 18)
redisInstance = make([]*Redis, 18)
}
index := db
if redisInstance[index] == nil {
redisOnce[index] = sync.Once{}
}
redisOnce[index].Do(func() {
config := SourceConfig("redis")
host := config.Get("host").MustString("127.0.0.1")
port := config.Get("port").MustInt(6379)
password := config.Get("password").MustString("")
timeout := config.Get("timeout").MustInt(0)
if db == 16 {
db = config.Get("db").MustInt(0)
}
redisInstance[index] = &Redis{}
redisInstance[index].Client = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", host, port),
Password: password,
DB: db,
WriteTimeout: time.Duration(timeout) * time.Second,
})
_, err := redisInstance[index].Ping().Result()
if err != nil {
_ = LogError(fmt.Sprintf("connect redis server was failed:%v", err.Error()))
}
})
return redisInstance[index]
}
// close redis connect
func RedisClose(selectDb ...int) {
db := 16
if len(selectDb) > 0 && selectDb[0] >= 0 {
db = selectDb[0]
}
if redisInstance[db] != nil {
_ = redisInstance[db].Close()
redisInstance[db] = nil
}
fmt.Println("close redis client:" + strconv.Itoa(db))
}
// make key with prefix
func RedisKey(key string, prefix string) string {
return prefix + "_" + key
}