Skip to content

Instantly share code, notes, and snippets.

@furdarius
Created December 19, 2018 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furdarius/19018f343f98a96c2983ef22424e4caa to your computer and use it in GitHub Desktop.
Save furdarius/19018f343f98a96c2983ef22424e4caa to your computer and use it in GitHub Desktop.
Redis Pool
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