1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-12 08:23:58 +02:00
go-micro/client/rpc_pool.go

92 lines
1.6 KiB
Go
Raw Normal View History

2016-05-13 16:58:53 +02:00
package client
import (
2016-06-07 01:46:14 +02:00
"fmt"
2016-05-13 16:58:53 +02:00
"sync"
2016-06-07 00:37:52 +02:00
"time"
2016-05-13 16:58:53 +02:00
"github.com/micro/go-micro/transport"
)
type pool struct {
2016-06-07 01:46:14 +02:00
size int
ttl int64
2016-05-13 16:58:53 +02:00
sync.Mutex
conns map[string][]*poolConn
}
type poolConn struct {
transport.Client
2016-06-07 00:37:52 +02:00
created int64
2016-05-13 16:58:53 +02:00
}
2016-06-07 01:46:14 +02:00
func newPool(size int, ttl time.Duration) *pool {
2016-05-13 16:58:53 +02:00
return &pool{
2016-06-07 01:46:14 +02:00
size: size,
ttl: int64(ttl.Seconds()),
2016-05-13 16:58:53 +02: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 00:37:52 +02: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 01:46:14 +02:00
if d := now - conn.created; d > p.ttl {
2016-06-07 00:37:52 +02:00
conn.Client.Close()
continue
2016-05-13 16:58:53 +02:00
}
2016-06-07 00:37:52 +02:00
// we got a good conn, lets unlock and return it
p.Unlock()
2016-06-07 01:46:14 +02:00
fmt.Println("old conn")
2016-06-07 00:37:52 +02:00
return conn, nil
2016-05-13 16:58:53 +02:00
}
p.Unlock()
2016-06-07 00:37:52 +02:00
2016-06-07 01:46:14 +02:00
fmt.Println("new conn")
2016-06-07 00:37:52 +02: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 16:58:53 +02:00
}
func (p *pool) release(addr string, conn *poolConn, err error) {
2016-06-07 00:37:52 +02:00
// don't store the conn if it has errored
2016-05-13 16:58:53 +02:00
if err != nil {
conn.Client.Close()
return
}
2016-06-07 00:37:52 +02:00
// otherwise put it back for reuse
2016-05-13 16:58:53 +02:00
p.Lock()
conns := p.conns[addr]
2016-06-07 01:46:14 +02:00
if len(conns) >= p.size {
2016-05-13 19:24:01 +02:00
p.Unlock()
2016-05-13 16:58:53 +02:00
conn.Client.Close()
return
}
p.conns[addr] = append(conns, conn)
p.Unlock()
}