/
service.go
57 lines (49 loc) · 1.41 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
package main
import (
"context"
"net"
"time"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
conf "github.com/amazingchow/consistent-hashing-service-provider/internal/config"
pb_api "github.com/amazingchow/consistent-hashing-service-provider/pb/api"
)
func serveGPRC(ctx context.Context, srv *consistentHashingServiceServer, cfg *conf.Node) {
l, err := net.Listen("tcp", cfg.GRPCEndpoint)
if err != nil {
log.Fatal().Err(err).Msg("failed to start grpc service")
}
opts := []grpc.ServerOption{
grpc.MaxSendMsgSize(64 * 1024 * 1024),
grpc.MaxRecvMsgSize(64 * 1024 * 1024),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 1 * time.Minute,
PermitWithoutStream: true,
}),
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: 10 * time.Minute,
Timeout: 20 * time.Second,
}),
}
grpcServer := grpc.NewServer(opts...)
pb_api.RegisterConsistentHashingServiceServer(grpcServer, srv)
// Register reflection service on gRPC server.
reflection.Register(grpcServer)
log.Info().Msgf("grpc service is listening at \x1b[1;31m%s\x1b[0m", cfg.GRPCEndpoint)
go func() {
if err := grpcServer.Serve(l); err != nil {
log.Warn().Err(err)
}
}()
GRPC_LOOP:
for { // nolint
select {
case <-ctx.Done():
break GRPC_LOOP
}
}
grpcServer.GracefulStop()
log.Info().Msg("stop grpc service")
}