You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/zrpc/internal/rpcserver.go

97 lines
2.4 KiB
Go

4 years ago
package internal
4 years ago
import (
"net"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/zrpc/internal/serverinterceptors"
4 years ago
"google.golang.org/grpc"
"google.golang.org/grpc/health/grpc_health_v1"
4 years ago
)
type (
// ServerOption defines the method to customize a rpcServerOptions.
4 years ago
ServerOption func(options *rpcServerOptions)
rpcServerOptions struct {
metrics *stat.Metrics
4 years ago
}
rpcServer struct {
name string
4 years ago
*baseRpcServer
}
)
func init() {
InitLogger()
}
// NewRpcServer returns a Server.
4 years ago
func NewRpcServer(address string, opts ...ServerOption) Server {
var options rpcServerOptions
for _, opt := range opts {
opt(&options)
}
if options.metrics == nil {
options.metrics = stat.NewMetrics(address)
}
return &rpcServer{
baseRpcServer: newBaseRpcServer(address, &options),
4 years ago
}
}
func (s *rpcServer) SetName(name string) {
s.name = name
4 years ago
s.baseRpcServer.SetName(name)
}
func (s *rpcServer) Start(register RegisterFn) error {
lis, err := net.Listen("tcp", s.address)
if err != nil {
return err
}
unaryInterceptors := []grpc.UnaryServerInterceptor{
serverinterceptors.UnaryTracingInterceptor,
serverinterceptors.UnaryCrashInterceptor,
4 years ago
serverinterceptors.UnaryStatInterceptor(s.metrics),
serverinterceptors.UnaryPrometheusInterceptor,
serverinterceptors.UnaryBreakerInterceptor,
4 years ago
}
unaryInterceptors = append(unaryInterceptors, s.unaryInterceptors...)
streamInterceptors := []grpc.StreamServerInterceptor{
serverinterceptors.StreamTracingInterceptor,
4 years ago
serverinterceptors.StreamCrashInterceptor,
3 years ago
serverinterceptors.StreamBreakerInterceptor,
4 years ago
}
streamInterceptors = append(streamInterceptors, s.streamInterceptors...)
options := append(s.options, WithUnaryServerInterceptors(unaryInterceptors...),
WithStreamServerInterceptors(streamInterceptors...))
server := grpc.NewServer(options...)
register(server)
// register the health check service
grpc_health_v1.RegisterHealthServer(server, s.health)
s.health.Resume()
// we need to make sure all others are wrapped up,
4 years ago
// so we do graceful stop at shutdown phase instead of wrap up phase
waitForCalled := proc.AddWrapUpListener(func() {
s.health.Shutdown()
4 years ago
server.GracefulStop()
})
defer waitForCalled()
4 years ago
return server.Serve(lis)
4 years ago
}
// WithMetrics returns a func that sets metrics to a Server.
4 years ago
func WithMetrics(metrics *stat.Metrics) ServerOption {
return func(options *rpcServerOptions) {
options.metrics = metrics
}
}