-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredispool.go
91 lines (81 loc) · 2.27 KB
/
redispool.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
package main
import (
"context"
"time"
"github.com/gomodule/redigo/redis"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"vitess.io/vitess/go/pools"
)
// These constants to be used as keys.
const (
RKeyJwtKey = "ych:jwtkey"
RKeyWorkers = "ych:workers"
RKeyStatFailed = "ych:stat:failed:"
RKeyStatProcessed = "ych:stat:processed:"
RKeyServers = "ych:servers"
RKeyServerQueue = "ych:queue:"
RKeyServerGroups = "ych:server_groups:"
RKeyServerSessions = "ych:server_sessions:"
RKeySessionsUsers = "ych:sessions_users"
RKeySessionsServers = "ych:sessions_servers"
RKeyUserSessions = "ych:user_sessions:"
RKeyUserExpirations = "ych:user_expirations:"
RKeyGroupSessions = "ych:group_sessions:"
RKeyGroupExpirations = "ych:group_expirations:"
RKeyQueue = "ych:queue:"
RKeyNS = "ych:"
)
// InitRedisPool initialization
func InitRedisPool() error {
Env.RedisPool = newRedisPool(Conf.Redis, 1, 10, 5*time.Minute)
switch val := RedisDo("GET", RKeyJwtKey).(type) {
case []byte:
Env.JwtKey = string(val)
}
if Env.JwtKey == "" {
uuid_obj, _ := uuid.NewUUID()
Env.JwtKey = uuid_obj.String()
RedisDo("SET", RKeyJwtKey, Env.JwtKey)
}
RegisterServer()
return nil
}
type RedisConn struct {
redis.Conn
}
func (r *RedisConn) Close() {
_ = r.Conn.Close()
}
func newRedisFactory(uri string) pools.Factory {
return func() (pools.Resource, error) {
return redisConnFromURI(uri)
}
}
func newRedisPool(uri string, capacity int, maxCapacity int, idleTimout time.Duration) *pools.ResourcePool {
return pools.NewResourcePool(newRedisFactory(uri), capacity, maxCapacity, idleTimout)
}
func redisConnFromURI(conn_str string) (*RedisConn, error) {
var dial_opts []redis.DialOption
dial_opts = append(dial_opts, redis.DialClientName("backws"))
conn, err := redis.Dial("tcp", conn_str, dial_opts...)
if err != nil {
return nil, err
}
return &RedisConn{Conn: conn}, nil
}
// RedisDo invoke a redis command
func RedisDo(cmd string, args ...interface{}) interface{} {
ctx := context.TODO()
res, err := Env.RedisPool.Get(ctx)
if err != nil {
log.Fatal(err)
}
defer Env.RedisPool.Put(res)
c := res.(*RedisConn).Conn
val, err := c.Do(cmd, args...)
if err != nil {
log.Fatal(err)
}
return val
}