-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
132 lines (106 loc) · 2.55 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package grpcpool
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/hunyxv/grpcpool/internal"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
var id int32
// LogicConn grpc 逻辑连接接口
type LogicConn interface {
Conn() grpc.ClientConnInterface
t()
}
var _ LogicConn = (*logicConn)(nil)
type logicConn struct {
grpc.ClientConnInterface
gconn *grpcConn
}
func (lc logicConn) Conn() grpc.ClientConnInterface {
return lc
}
func (logicConn) t() {}
var logicConnPool = sync.Pool{
New: func() interface{} { return logicConn{} },
}
type grpcConn struct {
p *Pool
conn *grpc.ClientConn
id int32
maxStreamsClient int
clientIdleTimeout time.Duration
current int32 // 当前剩余可用
lock sync.Locker
ts time.Time
}
func newGrpcConn(p *Pool, conn *grpc.ClientConn) *grpcConn {
return &grpcConn{
id: atomic.AddInt32(&id, 1),
p: p,
conn: conn,
maxStreamsClient: p.opt.MaxStreamsClient,
clientIdleTimeout: p.opt.ClientIdleTimeout,
current: int32(p.opt.MaxStreamsClient),
lock: internal.NewSpinLock(),
ts: time.Now(),
}
}
func (gc *grpcConn) get() (lc LogicConn, err error) {
current := atomic.LoadInt32(&gc.current)
if current == 0 {
err = errGrpcOverload
return
}
gc.lock.Lock()
defer gc.lock.Unlock()
if gc.conn.GetState() == connectivity.Shutdown {
err = ErrConnClosed
return
}
if gc.current == 0 {
err = errGrpcOverload
return
}
gc.ts = time.Now()
atomic.AddInt32(&gc.current, -1)
logicconn := logicConnPool.Get().(logicConn)
logicconn.gconn = gc
logicconn.ClientConnInterface = gc.conn
if gc.p.opt.Debug {
connection.WithLabelValues(fmt.Sprintf("conn-%d", gc.id)).Add(1)
}
return logicconn, nil
}
func (gc *grpcConn) recycle(lc logicConn) {
current := atomic.AddInt32(&gc.current, 1)
if int(current) > gc.maxStreamsClient {
panic("Unknown error")
}
if gc.p.opt.Debug {
connection.WithLabelValues(fmt.Sprintf("conn-%d", gc.id)).Sub(1)
}
lc.gconn = nil
lc.ClientConnInterface = nil
logicConnPool.Put(lc)
}
func (gc *grpcConn) isClosed() bool {
return gc.conn.GetState() == connectivity.Shutdown
}
func (gc *grpcConn) isIdle() bool {
return int(atomic.LoadInt32(&gc.current)) == gc.maxStreamsClient
}
func (gc *grpcConn) isTimeout() bool {
return time.Now().Sub(gc.ts) > gc.clientIdleTimeout
}
func (gc *grpcConn) close() (err error) {
gc.lock.Lock()
defer gc.lock.Unlock()
err = gc.conn.Close()
if err != nil {
return
}
return
}