-
Notifications
You must be signed in to change notification settings - Fork 2
/
mux.conn.grpc.go
85 lines (76 loc) · 1.68 KB
/
mux.conn.grpc.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
package main
import (
"context"
"fmt"
"pome/define"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
)
/*
连接复用, 节点之间的 http2 连接可以复用
连接与 node 结构体绑定
*/
type configConnDial struct {
KeepAlive time.Duration
KeepAliveTimeout time.Duration
DialTimeOut time.Duration
LeaseTimeOut int64
}
type nodeGRPC node
type NodePartConn struct {
conn *grpc.ClientConn
}
func (n *nodeGRPC) Conn(ctx context.Context) (*grpc.ClientConn, int, error) {
if n.conn != nil && n.active() {
return n.conn, -1, nil
}
n.lock.Lock()
defer n.lock.Unlock()
if n.conn != nil && n.active() {
return n.conn, -1, nil
}
//close old conn
if n.conn != nil {
n.conn.Close()
}
// new c
var addr = n.addr
if addr == "127.0.0.1" {
addr += fmt.Sprintf(":%d", define.ServicePortGRPC)
} else {
addr += fmt.Sprintf(":%d", define.SidecarPortOuterGRPC)
}
start := time.Now()
conn, err := grpc.DialContext(
ctx,
addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: CONFIG.configConnDial.KeepAlive,
Timeout: CONFIG.configConnDial.KeepAliveTimeout,
}))
if err != nil {
return nil, -1, err
}
elapsed := time.Since(start)
n.conn = conn
return conn, int(elapsed.Milliseconds()), nil
}
func (n *nodeGRPC) active() bool {
switch n.conn.GetState() {
case connectivity.TransientFailure, connectivity.Shutdown:
return false
}
return true
}
func (n *nodeGRPC) close() {
n.lock.Lock()
if n.conn != nil {
n.conn.Close()
}
n.lock.Unlock()
}