redis/internal/pool/pool_sticky.go

124 lines
1.8 KiB
Go
Raw Normal View History

package pool
import "sync"
type StickyConnPool struct {
pool *ConnPool
reusable bool
cn *Conn
closed bool
2017-01-28 11:53:10 +03:00
mu sync.Mutex
}
var _ Pooler = (*StickyConnPool)(nil)
func NewStickyConnPool(pool *ConnPool, reusable bool) *StickyConnPool {
return &StickyConnPool{
pool: pool,
reusable: reusable,
}
}
func (p *StickyConnPool) NewConn() (*Conn, error) {
panic("not implemented")
}
func (p *StickyConnPool) CloseConn(*Conn) error {
panic("not implemented")
}
2016-09-29 15:07:04 +03:00
func (p *StickyConnPool) Get() (*Conn, bool, error) {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
2016-09-29 15:07:04 +03:00
return nil, false, ErrClosed
}
if p.cn != nil {
2016-09-29 15:07:04 +03:00
return p.cn, false, nil
}
2016-09-29 15:07:04 +03:00
cn, _, err := p.pool.Get()
if err != nil {
2016-09-29 15:07:04 +03:00
return nil, false, err
}
p.cn = cn
2016-09-29 15:07:04 +03:00
return cn, true, nil
}
func (p *StickyConnPool) putUpstream() (err error) {
err = p.pool.Put(p.cn)
p.cn = nil
return err
}
func (p *StickyConnPool) Put(cn *Conn) error {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return ErrClosed
}
return nil
}
func (p *StickyConnPool) removeUpstream() error {
err := p.pool.Remove(p.cn)
p.cn = nil
return err
}
func (p *StickyConnPool) Remove(cn *Conn) error {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return nil
}
return p.removeUpstream()
}
func (p *StickyConnPool) Len() int {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.cn == nil {
return 0
}
return 1
}
func (p *StickyConnPool) FreeLen() int {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.cn == nil {
return 1
}
return 0
}
func (p *StickyConnPool) Stats() *Stats {
return nil
}
func (p *StickyConnPool) Close() error {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return ErrClosed
}
p.closed = true
var err error
if p.cn != nil {
if p.reusable {
err = p.putUpstream()
} else {
err = p.removeUpstream()
}
}
return err
}