redis_pool/pool.go

96 lines
1.5 KiB
Go
Raw Normal View History

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