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
| // discovery provider
type discovery struct {
*api.Client
dialopts []grpc.DialOption
}
// NewConsulDiscovery returns discovery
func NewConsulDiscovery(cfg Config) (Discovery, error) {
config := api.DefaultConfig()
config.Address = fmt.Sprintf("%s:%s", cfg.Host, cfg.Port)
c, err := api.NewClient(config)
if err != nil {
return nil, err
}
opts := []grpc.DialOption{
grpc.WithInsecure(),
grpc.WithBlock(),
}
if cfg.Tracer != nil {
opts = append(opts, grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(cfg.Tracer)))
opts = append(opts, grpc.WithStreamInterceptor(otgrpc.OpenTracingStreamClientInterceptor(cfg.Tracer)))
}
return discovery{c, opts}, nil
}
// Dial grpc server
func (c discovery) Dial(name string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
r, err := lb.NewResolver(c.Client, name, "")
if err != nil {
return nil, fmt.Errorf("Create balancer resolver for service %s failed. Error: %v", name, err)
}
c.dialopts = append(c.dialopts, grpc.WithBalancer(grpc.RoundRobin(r)))
c.dialopts = append(c.dialopts, opts...)
conn, err := grpc.Dial("", c.dialopts...)
if err != nil {
return nil, fmt.Errorf("Failed to dial %s: %v", name, err)
}
return conn, nil
}
|