micro/client/rpc_pool.go

92 lines
1.6 KiB
Go
Raw Normal View History

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
"github.com/micro/go-micro/transport"
)
type pool struct {
tr transport.Transport
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
}
var (
2016-06-07 01:37:52 +03:00
// only hold on to this many conns
2016-05-13 17:58:53 +03:00
maxIdleConn = 2
2016-06-07 01:37:52 +03:00
// only hold on to the conn for this period
maxLifeTime = int64(60)
2016-05-13 17:58:53 +03:00
)
func newPool() *pool {
return &pool{
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
if d := now - conn.created; d > maxLifeTime {
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]
if len(conns) >= maxIdleConn {
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()
}