/
base_redis.go
108 lines (87 loc) · 2.22 KB
/
base_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
99
100
101
102
103
104
105
106
107
108
package myrds
import (
"fmt"
"log"
"github.com/gomodule/redigo/redis"
"github.com/gookit/config/v2"
"github.com/inhere/go-web-skeleton/app"
"github.com/inhere/go-web-skeleton/app/clog"
"github.com/inhere/go-web-skeleton/app/helper"
"github.com/sirupsen/logrus"
)
type rdsConfig struct {
Server string
Auth string
Db int
Disable bool
}
var (
cfg rdsConfig
pool *redis.Pool
)
// redisPrefix
const redisPrefix = "feeds:"
// GenRedisKey Gen redis key
func GenRedisKey(tpl string, keys ...interface{}) string {
if len(keys) == 0 {
return redisPrefix + tpl
}
return redisPrefix + fmt.Sprintf(tpl, keys...)
}
// init redis connection pool
// redigo doc https://godoc.org/github.com/gomodule/redigo/redis#pkg-examples
func InitRedis() (err error) {
// 从配置文件获取redis的ip以及db
err = config.MapStruct("redis", &cfg)
if err != nil {
return
}
if cfg.Disable {
clog.Debugf("redis is disabled, skip init redis connection")
return
}
fmt.Printf("redis - server=%s db=%d auth=%s\n", cfg.Server, cfg.Db, cfg.Auth)
// 建立连接池
pool = helper.NewRedisPool(cfg.Server, cfg.Auth, cfg.Db)
return
}
// ClosePool close redis pool
func ClosePool() error {
if cfg.Disable {
return nil
}
return pool.Close()
}
// Connection return redis connection.
// Usage:
// conn := redis.Connection()
// defer conn.Close()
// ... do something ...
func Connection() redis.Conn {
logrus.Info("get new redis connection from pool") // zap.Namespace("context"),
// zap.Int("IdleCount", pool.IdleCount()),
// zap.Int("ActiveCount", pool.ActiveCount()),
// 记录操作日志
if app.Debug {
w := logrus.StandardLogger().Writer()
return redis.NewLoggingConn(pool.Get(), log.New(w, "", 0), "rds")
}
return pool.Get()
}
// WithConnection 公共方法,使用 collection 对象
// Usage:
// error = redis.WithConnection(func (c redis.Conn) error {
// ... do something ...
// })
func WithConnection(fn func(c redis.Conn) (interface{}, error)) (interface{}, error) {
conn := Connection()
defer conn.Close()
return fn(conn)
}
// HasZSet
func HasZSet(key string) bool {
count, _ := redis.Int(WithConnection(func(c redis.Conn) (interface{}, error) {
return c.Do("zCard", key)
}))
return count > 0
}