redis/internal/pool/pool_sticky.go

113 lines
1.5 KiB
Go
Raw Normal View History

package pool
2019-06-04 14:05:29 +03:00
import (
"context"
"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")
}
2019-06-04 14:05:29 +03:00
func (p *StickyConnPool) Get(c context.Context) (*Conn, error) {
2017-01-28 11:53:10 +03:00
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
2018-05-28 17:27:24 +03:00
return nil, ErrClosed
}
if p.cn != nil {
2018-05-28 17:27:24 +03:00
return p.cn, nil
}
2019-06-04 14:05:29 +03:00
cn, err := p.pool.Get(c)
if err != nil {
2018-05-28 17:27:24 +03:00
return nil, err
}
2018-05-28 17:27:24 +03:00
p.cn = cn
2018-05-28 17:27:24 +03:00
return cn, nil
}
2018-05-28 17:27:24 +03:00
func (p *StickyConnPool) putUpstream() {
p.pool.Put(p.cn)
p.cn = nil
}
2018-05-28 17:27:24 +03:00
func (p *StickyConnPool) Put(cn *Conn) {}
2018-05-28 17:27:24 +03:00
func (p *StickyConnPool) removeUpstream() {
p.pool.Remove(p.cn)
p.cn = nil
}
2018-05-28 17:27:24 +03:00
func (p *StickyConnPool) Remove(cn *Conn) {
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
}
2018-05-28 17:27:24 +03:00
func (p *StickyConnPool) IdleLen() 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
2018-05-28 17:27:24 +03:00
if p.cn != nil {
if p.reusable {
2018-05-28 17:27:24 +03:00
p.putUpstream()
} else {
2018-05-28 17:27:24 +03:00
p.removeUpstream()
}
}
2018-05-28 17:27:24 +03:00
return nil
}