1
0

server.go 1.8 KB

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