File tree Expand file tree Collapse file tree 2 files changed +46
-12
lines changed Expand file tree Collapse file tree 2 files changed +46
-12
lines changed Original file line number Diff line number Diff line change @@ -112,18 +112,25 @@ func (p *ConnPool) checkMinIdleConns() {
112112 return
113113 }
114114 for p .poolSize < p .cfg .PoolSize && p .idleConnsLen < p .cfg .MinIdleConns {
115- p .poolSize ++
116- p .idleConnsLen ++
117-
118- go func () {
119- err := p .addIdleConn ()
120- if err != nil && err != ErrClosed {
121- p .connsMu .Lock ()
122- p .poolSize --
123- p .idleConnsLen --
124- p .connsMu .Unlock ()
125- }
126- }()
115+ select {
116+ case p .queue <- struct {}{}:
117+ p .poolSize ++
118+ p .idleConnsLen ++
119+
120+ go func () {
121+ err := p .addIdleConn ()
122+ if err != nil && err != ErrClosed {
123+ p .connsMu .Lock ()
124+ p .poolSize --
125+ p .idleConnsLen --
126+ p .connsMu .Unlock ()
127+ }
128+
129+ p .freeTurn ()
130+ }()
131+ default :
132+ return
133+ }
127134 }
128135}
129136
@@ -401,6 +408,7 @@ func (p *ConnPool) removeConn(cn *Conn) {
401408 break
402409 }
403410 }
411+ atomic .AddUint32 (& p .stats .StaleConns , 1 )
404412}
405413
406414func (p * ConnPool ) closeConn (cn * Conn ) error {
Original file line number Diff line number Diff line change @@ -327,4 +327,30 @@ var _ = Describe("race", func() {
327327 }
328328 })
329329 })
330+
331+ It ("limit the number of connections" , func () {
332+ opt := & pool.Options {
333+ Dialer : func (ctx context.Context ) (net.Conn , error ) {
334+ return & net.TCPConn {}, nil
335+ },
336+ PoolSize : 1000 ,
337+ MinIdleConns : 50 ,
338+ PoolTimeout : 3 * time .Second ,
339+ }
340+ p := pool .NewConnPool (opt )
341+
342+ var wg sync.WaitGroup
343+ for i := 0 ; i < opt .PoolSize ; i ++ {
344+ wg .Add (1 )
345+ go func () {
346+ defer wg .Done ()
347+ _ , _ = p .Get (ctx )
348+ }()
349+ }
350+ wg .Wait ()
351+
352+ stats := p .Stats ()
353+ Expect (stats .IdleConns ).To (Equal (uint32 (0 )))
354+ Expect (stats .TotalConns ).To (Equal (uint32 (opt .PoolSize )))
355+ })
330356})
You can’t perform that action at this time.
0 commit comments