-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrpc_conn.go
74 lines (59 loc) · 1.73 KB
/
grpc_conn.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
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/6/9
Description :
-------------------------------------------------
*/
package zconn
import (
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/opentracing/opentracing-go"
"google.golang.org/grpc"
)
type grpcConnConnector struct{}
var _ IConnector = (*grpcConnConnector)(nil)
type GrpcConnConfig struct {
TracerEnable bool // 链路追踪
Addr string // 连接地址
Insecure bool // 不安全的
}
func (*grpcConnConnector) NewEmptyConfig() interface{} {
return new(GrpcConnConfig)
}
func (*grpcConnConnector) Connect(config interface{}) (instance interface{}, err error) {
conf := config.(*GrpcConnConfig)
var opts []grpc.DialOption
if conf.Insecure {
opts = append(opts, grpc.WithInsecure())
}
if conf.TracerEnable {
tracer := opentracing.GlobalTracer()
wrap_tracer := grpc_opentracing.WithTracer(tracer)
opts = append(opts, grpc.WithUnaryInterceptor(grpc_opentracing.UnaryClientInterceptor(wrap_tracer)))
}
conn, err := grpc.Dial(conf.Addr, opts...)
return conn, err
}
func (*grpcConnConnector) Close(instance interface{}) error {
c := instance.(*grpc.ClientConn)
return c.Close()
}
func AddGrpcConn(config interface{}, conn_name ...string) {
AddConfig(GrpcConn, config, conn_name...)
}
func GetGrpcConn(conn_name ...string) (*grpc.ClientConn, error) {
c, ok := GetConn(GrpcConn, conn_name...)
if !ok {
return nil, ErrNoConn
}
if !c.IsConnect() {
return nil, ErrConnNotConnected
}
return c.Instance().(*grpc.ClientConn), nil
}
func MustGrpcConn(conn_name ...string) *grpc.ClientConn {
c, err := GetGrpcConn(conn_name...)
panicOnErr(err)
return c
}