-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
executable file
·109 lines (94 loc) · 2.21 KB
/
client.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
package grpcpool
import (
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
// ClientConn is the basic unit in the pool
type ClientConn struct {
*grpc.ClientConn
pool *Pool
inUse int
timeUsed time.Time
timeInitiated time.Time
mu sync.RWMutex
}
// close a ClientConn when inuse == 1
// if inuse != 1 there is a new goroutine to watch the ClientConn until close it
func (client *ClientConn) close() error {
if client.inUse <= 0 {
return client.ClientConn.Close()
}
go client.closeWatch()
return nil
}
// The watch function is used to close the gRPC conn when inuse == 0 or timeout
func (client *ClientConn) closeWatch() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
if client.inUse <= 0 {
_ = client.ClientConn.Close()
break
}
if time.Now().Sub(client.timeUsed) > time.Minute { //long time no used so force to close
_ = client.ClientConn.Close()
}
}
}
func (client *ClientConn) use() {
client.mu.Lock()
client.timeUsed = time.Now()
client.inUse++
client.mu.Unlock()
}
// Put return the ClientConn when client call finish
func (client *ClientConn) Put() {
client.mu.Lock()
client.inUse--
client.mu.Unlock()
if !client.pool.requestQueue.isEmpty() && client.inUse < client.pool.opt.UsedPreConn {
clientChan := client.pool.requestQueue.dequeue().(chan *ClientConn)
clientChan <- client
close(clientChan)
return
}
if client.inUse == 0 {
client.pool.pushIdleClient(client)
}
}
// check if the gRPC conn state
func (client *ClientConn) active() bool {
switch client.ClientConn.GetState() {
case connectivity.Idle:
return true
case connectivity.Connecting:
return true
case connectivity.Ready:
return true
case connectivity.TransientFailure:
return false
case connectivity.Shutdown:
return false
default:
return false
}
}
func (client *ClientConn) waitForReady() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if client == nil {
break
} else if client.active() {
if client.pool.requestQueue.size() != 0 {
client.pool.clientQueue(client.pool.requestQueue.dequeue().(chan *ClientConn))
}
break
}
}
}
}