...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package grpctransport
16
17 import (
18 "context"
19 "fmt"
20 "sync/atomic"
21
22 "google.golang.org/grpc"
23 )
24
25
26
27
28
29
30 type GRPCClientConnPool interface {
31
32
33
34 Connection() *grpc.ClientConn
35
36
37
38 Len() int
39
40
41
42 Close() error
43
44 grpc.ClientConnInterface
45
46
47 private()
48 }
49
50
51 type singleConnPool struct {
52 *grpc.ClientConn
53 }
54
55 func (p *singleConnPool) Connection() *grpc.ClientConn { return p.ClientConn }
56 func (p *singleConnPool) Len() int { return 1 }
57 func (p *singleConnPool) private() {}
58
59 type roundRobinConnPool struct {
60 conns []*grpc.ClientConn
61
62 idx uint32
63 }
64
65 func (p *roundRobinConnPool) Len() int {
66 return len(p.conns)
67 }
68
69 func (p *roundRobinConnPool) Connection() *grpc.ClientConn {
70 i := atomic.AddUint32(&p.idx, 1)
71 return p.conns[i%uint32(len(p.conns))]
72 }
73
74 func (p *roundRobinConnPool) Close() error {
75 var errs multiError
76 for _, conn := range p.conns {
77 if err := conn.Close(); err != nil {
78 errs = append(errs, err)
79 }
80 }
81 if len(errs) == 0 {
82 return nil
83 }
84 return errs
85 }
86
87 func (p *roundRobinConnPool) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error {
88 return p.Connection().Invoke(ctx, method, args, reply, opts...)
89 }
90
91 func (p *roundRobinConnPool) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) {
92 return p.Connection().NewStream(ctx, desc, method, opts...)
93 }
94
95 func (p *roundRobinConnPool) private() {}
96
97
98 type multiError []error
99
100 func (m multiError) Error() string {
101 s, n := "", 0
102 for _, e := range m {
103 if e != nil {
104 if n == 0 {
105 s = e.Error()
106 }
107 n++
108 }
109 }
110 switch n {
111 case 0:
112 return "(0 errors)"
113 case 1:
114 return s
115 case 2:
116 return s + " (and 1 other error)"
117 }
118 return fmt.Sprintf("%s (and %d other errors)", s, n-1)
119 }
120
View as plain text