-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_client.go
61 lines (50 loc) · 1.19 KB
/
grpc_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
/**
* @Author: lidonglin
* @Description:
* @File: grpc_client.go
* @Version: 1.0.0
* @Date: 2023/12/10 15:03
*/
package tgrpc
import (
"context"
"github.com/choveylee/tlog"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type GrpcClient struct {
conn *grpc.ClientConn
}
func (p *GrpcClient) Conn() *grpc.ClientConn {
return p.conn
}
func NewGrpcClient(ctx context.Context, grpcOption GrpcOption, address string) (*GrpcClient, error) {
options := []grpc.DialOption{
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
grpc.WithChainUnaryInterceptor(
logClientInterceptor,
metaDataClientInterceptor,
),
grpc.WithAuthority(address),
grpc.WithTransportCredentials(insecure.NewCredentials()),
// grpc.WithBlock(),
}
options = append(options, grpcOption.options...)
conn, err := grpc.Dial(address, options...)
if err != nil {
return nil, err
}
go func() {
<-ctx.Done()
err := conn.Close()
if err != nil {
tlog.W(ctx).Err(err).Msgf("close grpc conn (%s) err (%v).",
address, err)
}
}()
grpcClient := &GrpcClient{
conn: conn,
}
return grpcClient, nil
}