1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-01-05 10:20:53 +02:00
go-micro/util/pool/default.go

129 lines
2.1 KiB
Go
Raw Normal View History

2019-07-28 19:56:18 +02:00
package pool
import (
"sync"
"time"
"github.com/google/uuid"
"go-micro.dev/v4/transport"
2019-07-28 19:56:18 +02:00
)
type pool struct {
size int
ttl time.Duration
tr transport.Transport
sync.Mutex
conns map[string][]*poolConn
}
type poolConn struct {
transport.Client
id string
created time.Time
}
func newPool(options Options) *pool {
return &pool{
size: options.Size,
tr: options.Transport,
ttl: options.TTL,
conns: make(map[string][]*poolConn),
}
}
func (p *pool) Close() error {
p.Lock()
defer p.Unlock()
var err error
2019-07-28 19:56:18 +02:00
for k, c := range p.conns {
for _, conn := range c {
if nerr := conn.Client.Close(); nerr != nil {
err = nerr
}
2019-07-28 19:56:18 +02:00
}
2019-07-28 19:56:18 +02:00
delete(p.conns, k)
}
return err
2019-07-28 19:56:18 +02:00
}
2022-09-30 16:27:07 +02:00
// NoOp the Close since we manage it.
2019-07-28 19:56:18 +02:00
func (p *poolConn) Close() error {
return nil
}
func (p *poolConn) Id() string {
return p.id
}
func (p *poolConn) Created() time.Time {
return p.created
}
func (p *pool) Get(addr string, opts ...transport.DialOption) (Conn, error) {
p.Lock()
conns := p.conns[addr]
// While we have conns check age and then return one
2019-07-28 19:56:18 +02:00
// 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
2019-07-28 19:56:18 +02:00
if d := time.Since(conn.Created()); d > p.ttl {
if err := conn.Client.Close(); err != nil {
p.Unlock()
return nil, err
}
2019-07-28 19:56:18 +02:00
continue
}
// We got a good conn, lets unlock and return it
2019-07-28 19:56:18 +02:00
p.Unlock()
return conn, nil
}
p.Unlock()
// create new conn
c, err := p.tr.Dial(addr, opts...)
if err != nil {
return nil, err
}
2019-07-28 19:56:18 +02:00
return &poolConn{
Client: c,
id: uuid.New().String(),
created: time.Now(),
}, nil
}
func (p *pool) Release(conn Conn, err error) error {
// don't store the conn if it has errored
if err != nil {
return conn.(*poolConn).Client.Close()
}
// otherwise put it back for reuse
p.Lock()
defer p.Unlock()
2019-07-28 19:56:18 +02:00
conns := p.conns[conn.Remote()]
if len(conns) >= p.size {
return conn.(*poolConn).Client.Close()
}
2019-07-28 19:56:18 +02:00
p.conns[conn.Remote()] = append(conns, conn.(*poolConn))
return nil
}