/
grpc_microservice.go
74 lines (64 loc) · 1.95 KB
/
grpc_microservice.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
package microservice
import (
context "context"
"net"
"github.com/bldsoft/geos/pkg/controller"
grpc_controller "github.com/bldsoft/geos/pkg/controller/grpc"
pb "github.com/bldsoft/geos/pkg/controller/grpc/proto"
"github.com/bldsoft/geos/pkg/microservice/middleware"
"github.com/bldsoft/gost/log"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc "google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
type GrpcMicroservice struct {
address string
grpcServer *grpc.Server
geoIpService controller.GeoIpService
geoNameService controller.GeoNameService
}
func NewGrpcMicroservice(address string, geoIpService controller.GeoIpService, geoNameService controller.GeoNameService) *GrpcMicroservice {
return &GrpcMicroservice{
address: address,
geoIpService: geoIpService,
geoNameService: geoNameService,
}
}
func (s *GrpcMicroservice) registerServices() {
geoIpController := grpc_controller.NewGeoIpController(s.geoIpService)
pb.RegisterGeoIpServiceServer(s.grpcServer, geoIpController)
geoNameController := grpc_controller.NewGeoNameController(s.geoNameService)
pb.RegisterGeoNameServiceServer(s.grpcServer, geoNameController)
}
func (s *GrpcMicroservice) Run() error {
grpclog.SetLoggerV2(middleware.Logger)
lis, err := net.Listen("tcp", s.address)
if err != nil {
return err
}
s.grpcServer = grpc.NewServer(grpc.UnaryInterceptor(
grpc_middleware.ChainUnaryServer(
middleware.RequestIDMiddleware,
middleware.RealIPMiddleware,
middleware.LoggerMiddleware(),
middleware.RecoveryMiddleware,
),
))
s.registerServices()
log.Infof("Grpc server started. Listening on %s", s.address)
defer log.Infof("Grpc server stopped")
return s.grpcServer.Serve(lis)
}
func (s *GrpcMicroservice) Stop(ctx context.Context) error {
stopped := make(chan struct{})
go func() {
defer close(stopped)
s.grpcServer.GracefulStop()
}()
select {
case <-stopped:
return nil
case <-ctx.Done():
return ctx.Err()
}
}