forked from stellar/go
/
init_redis.go
69 lines (54 loc) · 1.11 KB
/
init_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
package horizon
import (
"net/url"
"time"
"github.com/garyburd/redigo/redis"
"github.com/stellar/go/services/horizon/internal/log"
)
func initRedis(app *App) {
if app.config.RedisURL == "" {
return
}
redisURL, err := url.Parse(app.config.RedisURL)
if err != nil {
log.Panic(err)
}
app.redis = &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: dialRedis(redisURL),
TestOnBorrow: pingRedis,
}
// test the connection
c := app.redis.Get()
defer c.Close()
_, err = c.Do("PING")
if err != nil {
log.Panic(err)
}
}
func dialRedis(redisURL *url.URL) func() (redis.Conn, error) {
return func() (redis.Conn, error) {
c, err := redis.Dial("tcp", redisURL.Host)
if err != nil {
return nil, err
}
if redisURL.User == nil {
return c, err
}
if pass, ok := redisURL.User.Password(); ok {
if _, err := c.Do("AUTH", pass); err != nil {
c.Close()
return nil, err
}
}
return c, err
}
}
func pingRedis(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
}
func init() {
appInit.Add("redis", initRedis, "app-context", "log")
}