2016-05-13 17:58:53 +03:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2016-06-07 01:37:52 +03:00
|
|
|
"time"
|
2016-05-13 17:58:53 +03:00
|
|
|
|
2019-07-09 20:41:26 +03:00
|
|
|
"github.com/micro/go-micro/transport"
|
2016-05-13 17:58:53 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type pool struct {
|
2016-06-07 02:46:14 +03:00
|
|
|
size int
|
|
|
|
ttl int64
|
2016-05-13 17:58:53 +03:00
|
|
|
|
|
|
|
sync.Mutex
|
|
|
|
conns map[string][]*poolConn
|
|
|
|
}
|
|
|
|
|
|
|
|
type poolConn struct {
|
|
|
|
transport.Client
|
2016-06-07 01:37:52 +03:00
|
|
|
created int64
|
2016-05-13 17:58:53 +03:00
|
|
|
}
|
|
|
|
|
2016-06-07 02:46:14 +03:00
|
|
|
func newPool(size int, ttl time.Duration) *pool {
|
2016-05-13 17:58:53 +03:00
|
|
|
return &pool{
|
2016-06-07 02:46:14 +03:00
|
|
|
size: size,
|
|
|
|
ttl: int64(ttl.Seconds()),
|
2016-05-13 17:58:53 +03:00
|
|
|
conns: make(map[string][]*poolConn),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NoOp the Close since we manage it
|
|
|
|
func (p *poolConn) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *pool) getConn(addr string, tr transport.Transport, opts ...transport.DialOption) (*poolConn, error) {
|
|
|
|
p.Lock()
|
2016-06-07 01:37:52 +03:00
|
|
|
conns := p.conns[addr]
|
|
|
|
now := time.Now().Unix()
|
|
|
|
|
|
|
|
// while we have conns check age and then return one
|
|
|
|
// otherwise we'll create a new conn
|
|
|
|
for len(conns) > 0 {
|
|
|
|
conn := conns[len(conns)-1]
|
|
|
|
conns = conns[:len(conns)-1]
|
|
|
|
p.conns[addr] = conns
|
|
|
|
|
|
|
|
// if conn is old kill it and move on
|
2016-06-07 02:46:14 +03:00
|
|
|
if d := now - conn.created; d > p.ttl {
|
2016-06-07 01:37:52 +03:00
|
|
|
conn.Client.Close()
|
|
|
|
continue
|
2016-05-13 17:58:53 +03:00
|
|
|
}
|
2016-06-07 01:37:52 +03:00
|
|
|
|
|
|
|
// we got a good conn, lets unlock and return it
|
|
|
|
p.Unlock()
|
|
|
|
|
|
|
|
return conn, nil
|
2016-05-13 17:58:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
p.Unlock()
|
2016-06-07 01:37:52 +03:00
|
|
|
|
|
|
|
// create new conn
|
|
|
|
c, err := tr.Dial(addr, opts...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &poolConn{c, time.Now().Unix()}, nil
|
2016-05-13 17:58:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *pool) release(addr string, conn *poolConn, err error) {
|
2016-06-07 01:37:52 +03:00
|
|
|
// don't store the conn if it has errored
|
2016-05-13 17:58:53 +03:00
|
|
|
if err != nil {
|
|
|
|
conn.Client.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-06-07 01:37:52 +03:00
|
|
|
// otherwise put it back for reuse
|
2016-05-13 17:58:53 +03:00
|
|
|
p.Lock()
|
|
|
|
conns := p.conns[addr]
|
2016-06-07 02:46:14 +03:00
|
|
|
if len(conns) >= p.size {
|
2016-05-13 20:24:01 +03:00
|
|
|
p.Unlock()
|
2016-05-13 17:58:53 +03:00
|
|
|
conn.Client.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
p.conns[addr] = append(conns, conn)
|
|
|
|
p.Unlock()
|
|
|
|
}
|