server.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package internal
  2. import (
  3. "time"
  4. "github.com/zeromicro/go-zero/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. return &baseRpcServer{
  32. address: address,
  33. health: health.NewServer(),
  34. metrics: rpcServerOpts.metrics,
  35. options: []grpc.ServerOption{grpc.KeepaliveParams(keepalive.ServerParameters{
  36. MaxConnectionIdle: defaultConnectionIdleDuration,
  37. })},
  38. }
  39. }
  40. func (s *baseRpcServer) AddOptions(options ...grpc.ServerOption) {
  41. s.options = append(s.options, options...)
  42. }
  43. func (s *baseRpcServer) AddStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) {
  44. s.streamInterceptors = append(s.streamInterceptors, interceptors...)
  45. }
  46. func (s *baseRpcServer) AddUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) {
  47. s.unaryInterceptors = append(s.unaryInterceptors, interceptors...)
  48. }
  49. func (s *baseRpcServer) SetName(name string) {
  50. s.metrics.SetName(name)
  51. }