1
0
Fork 0

Add stats to connection pool

master
Philip O'Toole 3 years ago
parent 3a70db5150
commit ac1166fdca

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"net" "net"
"sync" "sync"
"sync/atomic"
) )
// channelPool implements the Pool interface based on buffered channels. // channelPool implements the Pool interface based on buffered channels.
@ -15,6 +16,7 @@ type channelPool struct {
// net.Conn generator // net.Conn generator
factory Factory factory Factory
nOpenConns int64
} }
// Factory is a function to create new connections. // Factory is a function to create new connections.
@ -81,6 +83,7 @@ func (c *channelPool) Get() (net.Conn, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
atomic.AddInt64(&c.nOpenConns, 1)
return c.wrapConn(conn), nil return c.wrapConn(conn), nil
} }
@ -98,6 +101,7 @@ func (c *channelPool) put(conn net.Conn) error {
if c.conns == nil { if c.conns == nil {
// pool is closed, close passed connection // pool is closed, close passed connection
atomic.AddInt64(&c.nOpenConns, -1)
return conn.Close() return conn.Close()
} }
@ -108,10 +112,13 @@ func (c *channelPool) put(conn net.Conn) error {
return nil return nil
default: default:
// pool is full, close passed connection // pool is full, close passed connection
atomic.AddInt64(&c.nOpenConns, -1)
return conn.Close() return conn.Close()
} }
} }
// Close closes every connection in the pool.
func (c *channelPool) Close() { func (c *channelPool) Close() {
c.mu.Lock() c.mu.Lock()
conns := c.conns conns := c.conns
@ -127,9 +134,21 @@ func (c *channelPool) Close() {
for conn := range conns { for conn := range conns {
conn.Close() conn.Close()
} }
atomic.AddInt64(&c.nOpenConns, 0)
} }
// Len() returns the number of idle connections.
func (c *channelPool) Len() int { func (c *channelPool) Len() int {
conns, _ := c.getConnsAndFactory() conns, _ := c.getConnsAndFactory()
return len(conns) return len(conns)
} }
// Stats returns stats for the pool.
func (c *channelPool) Stats() (map[string]interface{}, error) {
conns, _ := c.getConnsAndFactory()
return map[string]interface{}{
"idle": len(conns),
"open_connections": c.nOpenConns,
"max_open_connections": cap(conns),
}, nil
}

@ -25,4 +25,7 @@ type Pool interface {
// Len returns the current number of connections of the pool. // Len returns the current number of connections of the pool.
Len() int Len() int
// Stats returns stats about the pool.
Stats() (map[string]interface{}, error)
} }

Loading…
Cancel
Save