-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
grpc_pool.go
120 lines (100 loc) · 2.25 KB
/
grpc_pool.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
package grpcpool
import (
"context"
"strings"
"sync"
"time"
"github.com/ouqiang/gocron/internal/modules/app"
"github.com/ouqiang/gocron/internal/modules/rpc/auth"
"github.com/ouqiang/gocron/internal/modules/rpc/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
const (
backOffMaxDelay = 3 * time.Second
dialTimeout = 2 * time.Second
)
var (
Pool = &GRPCPool{
conns: make(map[string]*Client),
}
keepAliveParams = keepalive.ClientParameters{
Time: 20 * time.Second,
Timeout: 3 * time.Second,
PermitWithoutStream: true,
}
)
type Client struct {
conn *grpc.ClientConn
rpcClient rpc.TaskClient
}
type GRPCPool struct {
// map key格式 ip:port
conns map[string]*Client
mu sync.RWMutex
}
func (p *GRPCPool) Get(addr string) (rpc.TaskClient, error) {
p.mu.RLock()
client, ok := p.conns[addr]
p.mu.RUnlock()
if ok {
return client.rpcClient, nil
}
client, err := p.factory(addr)
if err != nil {
return nil, err
}
return client.rpcClient, nil
}
// 释放连接
func (p *GRPCPool) Release(addr string) {
p.mu.Lock()
defer p.mu.Unlock()
client, ok := p.conns[addr]
if !ok {
return
}
delete(p.conns, addr)
client.conn.Close()
}
// 创建连接
func (p *GRPCPool) factory(addr string) (*Client, error) {
p.mu.Lock()
defer p.mu.Unlock()
client, ok := p.conns[addr]
if ok {
return client, nil
}
opts := []grpc.DialOption{
grpc.WithKeepaliveParams(keepAliveParams),
grpc.WithBackoffMaxDelay(backOffMaxDelay),
}
if !app.Setting.EnableTLS {
opts = append(opts, grpc.WithInsecure())
} else {
server := strings.Split(addr, ":")
certificate := auth.Certificate{
CAFile: app.Setting.CAFile,
CertFile: app.Setting.CertFile,
KeyFile: app.Setting.KeyFile,
ServerName: server[0],
}
transportCreds, err := certificate.GetTransportCredsForClient()
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithTransportCredentials(transportCreds))
}
ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
defer cancel()
conn, err := grpc.DialContext(ctx, addr, opts...)
if err != nil {
return nil, err
}
client = &Client{
conn: conn,
rpcClient: rpc.NewTaskClient(conn),
}
p.conns[addr] = client
return client, nil
}