/
pool.go
209 lines (180 loc) · 5.06 KB
/
pool.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package cache
import (
"context"
"errors"
"net"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/gomodule/redigo/redis"
"github.com/mrz1836/go-cache/nrredis"
)
// Client is used to store the redis.Pool and additional fields/information
type Client struct {
DependencyScriptSha string // Stored SHA of the script after loaded
// Pool *redis.Pool // Redis pool for the client (get connections)
Pool nrredis.Pool // Redis pool for the client (get connections)
ScriptsLoaded []string // List of scripts that have been loaded
}
// Close closes the connection pool
func (c *Client) Close() {
if c.Pool != nil {
_ = c.Pool.Close()
}
c.Pool = nil
}
// CloseAll closes the connection pool and given connection
func (c *Client) CloseAll(conn redis.Conn) redis.Conn {
c.Close()
return c.CloseConnection(conn)
}
// GetConnection will return a connection from the pool. (convenience method)
// The connection must be closed when you're finished
// Deprecated: use GetConnectionWithContext()
func (c *Client) GetConnection() redis.Conn {
return c.Pool.Get()
}
// GetConnectionWithContext will return a connection from the pool. (convenience method)
// The connection must be closed when you're finished
func (c *Client) GetConnectionWithContext(ctx context.Context) (redis.Conn, error) {
if c.Pool != nil {
return c.Pool.GetContext(ctx)
}
return nil, errors.New("redis pool is nil")
}
// CloseConnection will close a previously open connection
func (c *Client) CloseConnection(conn redis.Conn) redis.Conn {
return CloseConnection(conn)
}
// CloseConnection will close a connection
func CloseConnection(conn redis.Conn) redis.Conn {
if conn != nil {
_ = conn.Close()
}
return nil
}
// Connect creates a new connection pool connected to the specified url
//
// Format of URL: redis://localhost:6379
func Connect(ctx context.Context, redisURL string,
maxActiveConnections, idleConnections int,
maxConnLifetime, idleTimeout time.Duration,
dependencyMode, newRelicEnabled bool, options ...redis.DialOption) (client *Client, err error) {
// Required param for dial
if len(redisURL) == 0 {
err = errors.New("missing required parameter: redisURL")
return
}
// Create the pool
redisPool := redis.Pool{
Dial: buildDialer(redisURL, options...),
IdleTimeout: idleTimeout,
MaxActive: maxActiveConnections,
MaxConnLifetime: maxConnLifetime,
MaxIdle: idleConnections,
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, doErr := c.Do(PingCommand)
return doErr
},
}
// Wrap if NewRelic is enabled
if newRelicEnabled {
var host, database, port string
if host, database, port, err = extractURL(redisURL); err != nil {
return
}
client = &Client{
Pool: nrredis.Wrap(
&redisPool,
nrredis.WithDBName(database),
nrredis.WithHost(host),
nrredis.WithPortPathOrID(port),
),
ScriptsLoaded: nil,
}
} else {
client = &Client{
Pool: &redisPool,
ScriptsLoaded: nil,
}
}
// Cleanup
cleanUp(client.Pool)
// Register scripts if enabled
if dependencyMode {
err = client.RegisterScripts(ctx)
}
return
}
// ConnectToURL connects via REDIS_URL and returns a single connection
//
// Deprecated: use Connect()
// Preferred method is "Connect()" to create a pool
// Source: "github.com/soveran/redisurl"
// Format of URL: redis://localhost:6379
func ConnectToURL(connectToURL string, options ...redis.DialOption) (conn redis.Conn, err error) {
// Parse the URL
var redisURL *url.URL
if redisURL, err = url.Parse(connectToURL); err != nil {
return
}
// Create the connection
if conn, err = redis.Dial("tcp", redisURL.Host, options...); err != nil {
return
}
// Attempt authentication if needed
if redisURL.User != nil {
if password, ok := redisURL.User.Password(); ok {
if _, err = conn.Do(AuthCommand, password); err != nil {
conn = nil
return
}
}
}
// Fire a select on DB
if len(redisURL.Path) > 1 {
_, err = conn.Do(SelectCommand, strings.TrimPrefix(redisURL.Path, "/"))
}
return
}
// buildDialer will build a redis connection from URL
func buildDialer(url string, options ...redis.DialOption) func() (redis.Conn, error) {
return func() (redis.Conn, error) {
return ConnectToURL(url, options...)
}
}
// cleanUp is fired after the pool is created
// Source: https://github.com/pete911/examples-redigo
// todo: is this really needed?
func cleanUp(pool nrredis.Pool) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
signal.Notify(c, syscall.SIGKILL)
go func(pool nrredis.Pool) {
<-c
_ = pool.Close()
os.Exit(0)
}(pool)
}
// extractURL will extract the parts of the redis url
func extractURL(redisURL string) (host, database, port string, err error) {
// Parse the URL
var u *url.URL
if u, err = url.Parse(redisURL); err != nil {
return
}
// Split the host and port
if host, port, err = net.SplitHostPort(u.Host); err != nil {
return
}
// Set the database
database = strings.Replace(u.RequestURI(), "/", "", -1)
return
}