This repository has been archived by the owner on Aug 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
conn_pool.go
64 lines (56 loc) · 1.62 KB
/
conn_pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package carbon
import (
"github.com/signalfx/golib/datapoint"
"github.com/signalfx/golib/errors"
"github.com/signalfx/golib/sfxclient"
"net"
"sync"
"sync/atomic"
)
// connPool pools connections for reuse
type connPool struct {
conns []net.Conn
mu sync.Mutex
stats struct {
reusuedConnections int64
returnedConnections int64
}
}
// Get a connection from the pool. Returns nil if there is none in the pool
func (pool *connPool) Get() net.Conn {
pool.mu.Lock()
defer pool.mu.Unlock()
if len(pool.conns) > 0 {
c := pool.conns[len(pool.conns)-1]
pool.conns = pool.conns[0 : len(pool.conns)-1]
atomic.AddInt64(&pool.stats.reusuedConnections, 1)
return c
}
return nil
}
func (pool *connPool) Datapoints() []*datapoint.Datapoint {
return []*datapoint.Datapoint{
sfxclient.Cumulative("reused_connections", map[string]string{"struct": "connPool"}, atomic.LoadInt64(&pool.stats.reusuedConnections)),
sfxclient.Cumulative("returned_connections", map[string]string{"struct": "connPool"}, atomic.LoadInt64(&pool.stats.returnedConnections)),
}
}
// Return a connection to the pool. Do not return closed or invalid connections
func (pool *connPool) Return(conn net.Conn) {
pool.mu.Lock()
defer pool.mu.Unlock()
atomic.AddInt64(&pool.stats.returnedConnections, 1)
pool.conns = append(pool.conns, conn)
}
// Close clears the connection pool
func (pool *connPool) Close() error {
var errs []error
for {
c := pool.Get()
if c == nil {
return errors.NewMultiErr(errs)
}
// Fix the reusuedConnections stat being incremented by Get()
atomic.AddInt64(&pool.stats.reusuedConnections, -1)
errs = append(errs, c.Close())
}
}