rpcserver.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package internal
  2. import (
  3. "net"
  4. "github.com/tal-tech/go-zero/core/proc"
  5. "github.com/tal-tech/go-zero/core/stat"
  6. "github.com/tal-tech/go-zero/zrpc/internal/serverinterceptors"
  7. "google.golang.org/grpc"
  8. )
  9. type (
  10. // ServerOption defines the method to customize a rpcServerOptions.
  11. ServerOption func(options *rpcServerOptions)
  12. rpcServerOptions struct {
  13. metrics *stat.Metrics
  14. }
  15. rpcServer struct {
  16. name string
  17. *baseRpcServer
  18. }
  19. )
  20. func init() {
  21. InitLogger()
  22. }
  23. // NewRpcServer returns a Server.
  24. func NewRpcServer(address string, opts ...ServerOption) Server {
  25. var options rpcServerOptions
  26. for _, opt := range opts {
  27. opt(&options)
  28. }
  29. if options.metrics == nil {
  30. options.metrics = stat.NewMetrics(address)
  31. }
  32. return &rpcServer{
  33. baseRpcServer: newBaseRpcServer(address, options.metrics),
  34. }
  35. }
  36. func (s *rpcServer) SetName(name string) {
  37. s.name = name
  38. s.baseRpcServer.SetName(name)
  39. }
  40. func (s *rpcServer) Start(register RegisterFn) error {
  41. lis, err := net.Listen("tcp", s.address)
  42. if err != nil {
  43. return err
  44. }
  45. unaryInterceptors := []grpc.UnaryServerInterceptor{
  46. serverinterceptors.UnaryTracingInterceptor(s.name),
  47. serverinterceptors.UnaryCrashInterceptor(),
  48. serverinterceptors.UnaryStatInterceptor(s.metrics),
  49. serverinterceptors.UnaryPrometheusInterceptor(),
  50. serverinterceptors.UnaryBreakerInterceptor(),
  51. }
  52. unaryInterceptors = append(unaryInterceptors, s.unaryInterceptors...)
  53. streamInterceptors := []grpc.StreamServerInterceptor{
  54. serverinterceptors.StreamCrashInterceptor,
  55. serverinterceptors.StreamBreakerInterceptor,
  56. }
  57. streamInterceptors = append(streamInterceptors, s.streamInterceptors...)
  58. options := append(s.options, WithUnaryServerInterceptors(unaryInterceptors...),
  59. WithStreamServerInterceptors(streamInterceptors...))
  60. server := grpc.NewServer(options...)
  61. register(server)
  62. // we need to make sure all others are wrapped up
  63. // so we do graceful stop at shutdown phase instead of wrap up phase
  64. waitForCalled := proc.AddWrapUpListener(func() {
  65. server.GracefulStop()
  66. })
  67. defer waitForCalled()
  68. return server.Serve(lis)
  69. }
  70. // WithMetrics returns a func that sets metrics to a Server.
  71. func WithMetrics(metrics *stat.Metrics) ServerOption {
  72. return func(options *rpcServerOptions) {
  73. options.metrics = metrics
  74. }
  75. }