-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
91 lines (71 loc) · 1.75 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
package grpcx
import (
"fmt"
"sync"
"google.golang.org/grpc"
)
// ClientCreator create a grpc client
type ClientCreator func(string, *grpc.ClientConn) interface{}
// GRPCClient is a grpc client
type GRPCClient struct {
sync.RWMutex
creator ClientCreator
opts *clientOptions
clients map[string]interface{}
conns map[string]*grpc.ClientConn
}
// NewGRPCClient returns a GRPC Client
func NewGRPCClient(creator ClientCreator, opts ...ClientOption) *GRPCClient {
copts := &clientOptions{}
for _, opt := range opts {
opt(copts)
}
return &GRPCClient{
opts: copts,
creator: creator,
clients: make(map[string]interface{}),
}
}
// Close close
func (c *GRPCClient) Close() error {
c.RLock()
defer c.RUnlock()
var err error
for _, conn := range c.conns {
err = conn.Close()
}
return err
}
// GetServiceClient returns a grpc client
func (c *GRPCClient) GetServiceClient(name string) (interface{}, error) {
c.RLock()
if cli, ok := c.clients[name]; ok {
c.RUnlock()
return cli, nil
}
c.RUnlock()
client, err := c.createClient(name)
if err != nil {
return nil, err
}
return client, nil
}
func (c *GRPCClient) createClient(name string) (interface{}, error) {
c.Lock()
defer c.Unlock()
if cli, ok := c.clients[name]; ok {
return cli, nil
}
var grpcOptions []grpc.DialOption
grpcOptions = append(grpcOptions, grpc.WithInsecure())
grpcOptions = append(grpcOptions, grpc.WithTimeout(c.opts.timeout))
grpcOptions = append(grpcOptions, grpc.WithBlock())
grpcOptions = append(grpcOptions, grpc.WithBalancer(grpc.RoundRobin(c.opts.resolver)))
conn, err := grpc.Dial(fmt.Sprintf("%s/%s", c.opts.prefix, name), grpcOptions...)
if err != nil {
return nil, err
}
cli := c.creator(name, conn)
c.clients[name] = cli
return cli, nil
}