Created
December 19, 2018 11:51
-
-
Save furdarius/19018f343f98a96c2983ef22424e4caa to your computer and use it in GitHub Desktop.
Redis Pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package redis | |
import ( | |
"net" | |
"strconv" | |
"time" | |
"github.com/garyburd/redigo/redis" | |
) | |
const healthCheckPeriod = 10 * time.Second | |
// PoolConfig is Redis pool configuration. | |
type PoolConfig struct { | |
// Host is Redis server host. | |
Host string `json:"host"` | |
// Port is Redis server port. | |
Port int `json:"port"` | |
// Password is password to use when connecting to Redis database. If empty then password not used. | |
Password string `json:"password"` | |
// DB is Redis database number. If zero then database 0 will be used. | |
DB int `json:"db"` | |
// PoolSize is a size of pool. | |
PoolSize int `json:"pool_size"` | |
} | |
// NewPool creates Redis pool. | |
func NewPool(c PoolConfig) *redis.Pool { | |
host := c.Host | |
if host == "" { | |
host = "localhost" | |
} | |
port := c.Port | |
if port == 0 { | |
port = 6379 | |
} | |
poolSize := c.PoolSize | |
if poolSize == 0 { | |
poolSize = 64 | |
} | |
maxIdle := 10 | |
if poolSize < maxIdle { | |
maxIdle = poolSize | |
} | |
password := c.Password | |
db := c.DB | |
addr := net.JoinHostPort(host, strconv.Itoa(port)) | |
return &redis.Pool{ | |
MaxIdle: maxIdle, | |
MaxActive: poolSize, | |
Wait: true, | |
IdleTimeout: 240 * time.Second, | |
Dial: func() (redis.Conn, error) { | |
conn, err := redis.Dial("tcp", addr, | |
// Read timeout on server should be greater than ping period. | |
redis.DialReadTimeout(healthCheckPeriod+10*time.Second), | |
redis.DialWriteTimeout(10*time.Second)) | |
if err != nil { | |
return nil, err | |
} | |
if password != "" { | |
if _, err = conn.Do("AUTH", password); err != nil { | |
_ = conn.Close() | |
return nil, err | |
} | |
} | |
if db != 0 { | |
if _, err = conn.Do("SELECT", db); err != nil { | |
_ = conn.Close() | |
return nil, err | |
} | |
} | |
return conn, nil | |
}, | |
TestOnBorrow: func(c redis.Conn, t time.Time) error { | |
if time.Since(t) < healthCheckPeriod { | |
return nil | |
} | |
_, err := c.Do("PING") | |
return err | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment