Skip to content

Commit

Permalink
fix: limit the number of connections created (#2441)
Browse files Browse the repository at this point in the history
* fix: limit the number of connections created

Signed-off-by: monkey92t <golang@88.com>
  • Loading branch information
monkey92t authored Feb 14, 2023
1 parent 0d30623 commit 3532f2a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 12 deletions.
32 changes: 20 additions & 12 deletions internal/pool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,25 @@ func (p *ConnPool) checkMinIdleConns() {
return
}
for p.poolSize < p.cfg.PoolSize && p.idleConnsLen < p.cfg.MinIdleConns {
p.poolSize++
p.idleConnsLen++

go func() {
err := p.addIdleConn()
if err != nil && err != ErrClosed {
p.connsMu.Lock()
p.poolSize--
p.idleConnsLen--
p.connsMu.Unlock()
}
}()
select {
case p.queue <- struct{}{}:
p.poolSize++
p.idleConnsLen++

go func() {
err := p.addIdleConn()
if err != nil && err != ErrClosed {
p.connsMu.Lock()
p.poolSize--
p.idleConnsLen--
p.connsMu.Unlock()
}

p.freeTurn()
}()
default:
return
}
}
}

Expand Down Expand Up @@ -401,6 +408,7 @@ func (p *ConnPool) removeConn(cn *Conn) {
break
}
}
atomic.AddUint32(&p.stats.StaleConns, 1)
}

func (p *ConnPool) closeConn(cn *Conn) error {
Expand Down
26 changes: 26 additions & 0 deletions internal/pool/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,4 +327,30 @@ var _ = Describe("race", func() {
}
})
})

It("limit the number of connections", func() {
opt := &pool.Options{
Dialer: func(ctx context.Context) (net.Conn, error) {
return &net.TCPConn{}, nil
},
PoolSize: 1000,
MinIdleConns: 50,
PoolTimeout: 3 * time.Second,
}
p := pool.NewConnPool(opt)

var wg sync.WaitGroup
for i := 0; i < opt.PoolSize; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = p.Get(ctx)
}()
}
wg.Wait()

stats := p.Stats()
Expect(stats.IdleConns).To(Equal(uint32(0)))
Expect(stats.TotalConns).To(Equal(uint32(opt.PoolSize)))
})
})

0 comments on commit 3532f2a

Please sign in to comment.