go-zero/zrpc/internal/rpcserver.go

90 lines
2.3 KiB
Go
Raw Normal View History

2020-07-29 18:06:57 +08:00
package internal
2020-07-26 17:09:05 +08:00
import (
"net"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/zrpc/internal/serverinterceptors"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
)
type (
2021-03-01 23:52:44 +08:00
// ServerOption defines the method to customize a rpcServerOptions.
2020-07-26 17:09:05 +08:00
ServerOption func(options *rpcServerOptions)
rpcServerOptions struct {
metrics *stat.Metrics
2020-07-26 17:09:05 +08:00
}
rpcServer struct {
name string
2020-07-26 17:09:05 +08:00
*baseRpcServer
}
)
func init() {
InitLogger()
}
2021-03-01 23:52:44 +08:00
// NewRpcServer returns a Server.
2020-07-26 17:09:05 +08:00
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),
2020-07-26 17:09:05 +08:00
}
}
func (s *rpcServer) SetName(name string) {
s.name = name
2020-07-26 17:09:05 +08:00
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,
2020-07-26 17:09:05 +08:00
serverinterceptors.UnaryStatInterceptor(s.metrics),
serverinterceptors.UnaryPrometheusInterceptor,
serverinterceptors.UnaryBreakerInterceptor,
2020-07-26 17:09:05 +08:00
}
unaryInterceptors = append(unaryInterceptors, s.unaryInterceptors...)
streamInterceptors := []grpc.StreamServerInterceptor{
serverinterceptors.StreamTracingInterceptor,
2020-07-26 17:09:05 +08:00
serverinterceptors.StreamCrashInterceptor,
2021-08-04 18:45:05 +08:00
serverinterceptors.StreamBreakerInterceptor,
2020-07-26 17:09:05 +08:00
}
streamInterceptors = append(streamInterceptors, s.streamInterceptors...)
options := append(s.options, WithUnaryServerInterceptors(unaryInterceptors...),
WithStreamServerInterceptors(streamInterceptors...))
server := grpc.NewServer(options...)
register(server)
// we need to make sure all others are wrapped up,
2020-07-26 17:09:05 +08:00
// so we do graceful stop at shutdown phase instead of wrap up phase
2020-11-08 13:08:00 +08:00
waitForCalled := proc.AddWrapUpListener(func() {
2020-07-26 17:09:05 +08:00
server.GracefulStop()
})
2020-11-08 13:08:00 +08:00
defer waitForCalled()
2020-07-26 17:09:05 +08:00
2020-11-08 13:08:00 +08:00
return server.Serve(lis)
2020-07-26 17:09:05 +08:00
}
2021-03-01 23:52:44 +08:00
// WithMetrics returns a func that sets metrics to a Server.
2020-07-26 17:09:05 +08:00
func WithMetrics(metrics *stat.Metrics) ServerOption {
return func(options *rpcServerOptions) {
options.metrics = metrics
}
}