-
Notifications
You must be signed in to change notification settings - Fork 2
/
conn.go
56 lines (48 loc) · 1.04 KB
/
conn.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
package grpcpool
import (
"errors"
"google.golang.org/grpc"
)
// connPool is that gRPC connection pool by buffered channel
type connPool struct {
conns chan *grpc.ClientConn
cg ConnGenerator
target string
opts []grpc.DialOption
}
// ConnGenerator is function type to generate a grpc connection function
type ConnGenerator func(target string, opts ...grpc.DialOption) (conn *grpc.ClientConn, err error)
func (c *connPool) get() (*grpc.ClientConn, error) {
select {
case conn := <-c.conns:
if conn == nil {
return nil, errors.New("connection is closed")
}
return conn, nil
default:
// channel is empty
conn, err := c.cg(c.target, c.opts...)
if err != nil {
return nil, err
}
return conn, nil
}
}
func (c *connPool) putBack(conn *grpc.ClientConn) error {
if conn == nil {
return errors.New("conn is nil")
}
select {
case c.conns <- conn:
return nil
default:
// channel if full
return conn.Close()
}
}
func (c *connPool) len() int {
return len(c.conns)
}
func (c *connPool) close() {
close(c.conns)
}