/
service.go
70 lines (60 loc) · 1.9 KB
/
service.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
/*
* @Author: lwnmengjing
* @Date: 2021/6/8 5:29 下午
* @Last Modified by: lwnmengjing
* @Last Modified time: 2021/6/8 5:29 下午
*/
package grpc
import (
"context"
"fmt"
"time"
middleware "github.com/grpc-ecosystem/go-grpc-middleware"
opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
log "github.com/maodapeng/server-core/logger"
"github.com/maodapeng/server-core/server/grpc/interceptors/logging"
reqtags "github.com/maodapeng/server-core/server/grpc/interceptors/request_tag"
"google.golang.org/grpc"
)
type Service struct {
Connection *grpc.ClientConn
CallTimeout time.Duration
}
func (e *Service) Dial(
endpoint string,
callTimeout time.Duration,
unary ...grpc.UnaryClientInterceptor) (err error) {
log.Infof("configure service with endpoint: %s", endpoint)
ctx, cancel := context.WithTimeout(context.Background(), callTimeout)
defer cancel()
if len(unary) == 0 {
unary = defaultUnaryClientInterceptors()
}
e.Connection, err = grpc.DialContext(ctx,
endpoint,
grpc.WithInsecure(),
grpc.WithStreamInterceptor(middleware.ChainStreamClient(defaultStreamClientInterceptors()...)),
grpc.WithUnaryInterceptor(middleware.ChainUnaryClient(unary...)),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true), grpc.MaxCallRecvMsgSize(defaultMaxMsgSize)),
)
if err != nil {
msg := fmt.Sprintf("connect gRPC service %s failed", endpoint)
log.Errorf(msg, err)
return fmt.Errorf("%w, "+msg, err)
}
return nil
}
func defaultUnaryClientInterceptors() []grpc.UnaryClientInterceptor {
return []grpc.UnaryClientInterceptor{
opentracing.UnaryClientInterceptor(),
logging.UnaryClientInterceptor(),
reqtags.UnaryClientInterceptor(),
}
}
func defaultStreamClientInterceptors() []grpc.StreamClientInterceptor {
return []grpc.StreamClientInterceptor{
opentracing.StreamClientInterceptor(),
logging.StreamClientInterceptor(),
reqtags.StreamClientInterceptor(),
}
}