/
redis.go
79 lines (60 loc) · 1.27 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
// Author : 船長 <erichsiao@awoo.com.tw>
package redis
import (
"errors"
"github.com/go-redis/redis"
)
var (
cfg *redis.Options
db *redis.Client
)
// setConfig : new redis options via go-models
// addr : must with port number. ex: '127.0.0.1:6379'
func setConfig(addr, pw string, db int) {
if cfg != nil {
panic("already had config !!")
}
cfg = &redis.Options{
Addr: addr,
Password: pw,
DB: db,
}
return
}
// setOriginConfig : set mysql config
func setOriginConfig(c *redis.Options) {
if c != nil {
cfg = c
}
}
// getConfig : return the config
func getConfig() *redis.Options {
return cfg
}
// openDB : open a new mysql connection
func openDB(c ...*redis.Options) (*redis.Client, error) {
if len(c) > 0 && c[0] != nil {
cfg = c[0]
}
if cfg == nil {
return nil, errors.New("Do NewConfig() first")
}
if db != nil {
return nil, errors.New("already connect to db")
}
db = redis.NewClient(cfg)
return db, nil
}
// openDBWithPoolConns : open a new mysql connection and pool conns
func openDBWithPoolConns(active, idle int) (*redis.Client, error) {
var err error
// setting connections pool
if cfg != nil {
cfg.PoolSize = active
cfg.MinIdleConns = idle
}
if db, err = openDB(); err != nil {
return nil, err
}
return db, nil
}