protect pollSize and idleConnsLen with mutex (#1105)

Fix poolSize and idleConnsLen when conn can't be created
This commit is contained in:
waterandair 2019-07-28 14:56:57 +08:00 committed by Vladimir Mihailenco
parent d190c8191e
commit 6cd6cd828f
1 changed files with 6 additions and 4 deletions

View File

@ -92,9 +92,7 @@ func NewConnPool(opt *Options) *ConnPool {
idleConns: make([]*Conn, 0, opt.PoolSize), idleConns: make([]*Conn, 0, opt.PoolSize),
} }
for i := 0; i < opt.MinIdleConns; i++ {
p.checkMinIdleConns() p.checkMinIdleConns()
}
if opt.IdleTimeout > 0 && opt.IdleCheckFrequency > 0 { if opt.IdleTimeout > 0 && opt.IdleCheckFrequency > 0 {
go p.reaper(opt.IdleCheckFrequency) go p.reaper(opt.IdleCheckFrequency)
@ -107,7 +105,7 @@ func (p *ConnPool) checkMinIdleConns() {
if p.opt.MinIdleConns == 0 { if p.opt.MinIdleConns == 0 {
return return
} }
if p.poolSize < p.opt.PoolSize && p.idleConnsLen < p.opt.MinIdleConns { for p.poolSize < p.opt.PoolSize && p.idleConnsLen < p.opt.MinIdleConns {
p.poolSize++ p.poolSize++
p.idleConnsLen++ p.idleConnsLen++
go p.addIdleConn() go p.addIdleConn()
@ -117,6 +115,10 @@ func (p *ConnPool) checkMinIdleConns() {
func (p *ConnPool) addIdleConn() { func (p *ConnPool) addIdleConn() {
cn, err := p.newConn(context.TODO(), true) cn, err := p.newConn(context.TODO(), true)
if err != nil { if err != nil {
p.connsMu.Lock()
p.poolSize--
p.idleConnsLen--
p.connsMu.Unlock()
return return
} }