github.com/lingyao2333/mo-zero@v1.4.1/zrpc/internal/server.go (about) 1 package internal 2 3 import ( 4 "time" 5 6 "github.com/lingyao2333/mo-zero/core/stat" 7 "google.golang.org/grpc" 8 "google.golang.org/grpc/health" 9 "google.golang.org/grpc/keepalive" 10 ) 11 12 const defaultConnectionIdleDuration = time.Minute * 5 13 14 type ( 15 // RegisterFn defines the method to register a server. 16 RegisterFn func(*grpc.Server) 17 18 // Server interface represents a rpc server. 19 Server interface { 20 AddOptions(options ...grpc.ServerOption) 21 AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) 22 AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) 23 SetName(string) 24 Start(register RegisterFn) error 25 } 26 27 baseRpcServer struct { 28 address string 29 health *health.Server 30 metrics *stat.Metrics 31 options []grpc.ServerOption 32 streamInterceptors []grpc.StreamServerInterceptor 33 unaryInterceptors []grpc.UnaryServerInterceptor 34 } 35 ) 36 37 func newBaseRpcServer(address string, rpcServerOpts *rpcServerOptions) *baseRpcServer { 38 var h *health.Server 39 if rpcServerOpts.health { 40 h = health.NewServer() 41 } 42 return &baseRpcServer{ 43 address: address, 44 health: h, 45 metrics: rpcServerOpts.metrics, 46 options: []grpc.ServerOption{grpc.KeepaliveParams(keepalive.ServerParameters{ 47 MaxConnectionIdle: defaultConnectionIdleDuration, 48 })}, 49 } 50 } 51 52 func (s *baseRpcServer) AddOptions(options ...grpc.ServerOption) { 53 s.options = append(s.options, options...) 54 } 55 56 func (s *baseRpcServer) AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) { 57 s.streamInterceptors = append(s.streamInterceptors, interceptors...) 58 } 59 60 func (s *baseRpcServer) AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) { 61 s.unaryInterceptors = append(s.unaryInterceptors, interceptors...) 62 } 63 64 func (s *baseRpcServer) SetName(name string) { 65 s.metrics.SetName(name) 66 }