redis_pool/pool.go
crusader 92571a0f27 ing
2017-11-10 15:15:00 +09:00

96 lines
1.5 KiB
Go

package redis_pool
import (
"fmt"
"sync"
"git.loafle.net/commons_go/logging"
"github.com/garyburd/redigo/redis"
)
type Pool interface {
Start() error
Stop()
Get() redis.Conn
Put(conn redis.Conn)
Capacity() int
Available() int
}
type pool struct {
ph PoolHandler
rp *redis.Pool
stopChan chan struct{}
stopWg sync.WaitGroup
}
func New(ph PoolHandler) Pool {
p := &pool{
ph: ph,
}
p.rp = &redis.Pool{
MaxIdle: ph.GetMaxIdle(),
MaxActive: ph.GetMaxCapacity(),
IdleTimeout: ph.GetIdleTimeout(),
Wait: ph.IsWait(),
Dial: ph.Dial,
}
return p
}
func (p *pool) Start() error {
if p.stopChan != nil {
panic("Redis Pool: pool is already running. Stop it before starting it again")
}
if nil == p.ph {
panic("Redis Pool: pool handler must be specified.")
}
p.ph.Validate()
p.stopChan = make(chan struct{})
return nil
}
func (p *pool) Stop() {
if p.stopChan == nil {
panic("Redis Pool: pool must be started before stopping it")
}
if err := p.rp.Close(); nil != err {
logging.Logger().Error(fmt.Sprintf("Redis Pool: redis pool stop error %v", err))
}
close(p.stopChan)
p.stopChan = nil
}
func (p *pool) Get() redis.Conn {
return p.rp.Get()
}
func (p *pool) Put(conn redis.Conn) {
if nil == conn {
return
}
if err := conn.Close(); nil != err {
logging.Logger().Error(fmt.Sprintf("Redis Pool: redis connection close error %v", err))
}
}
func (p *pool) Capacity() int {
return p.rp.ActiveCount()
}
func (p *pool) Available() int {
return p.rp.IdleCount()
}