go-zero/zrpc/internal/rpcserver.go

87 lines
2.0 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 (
"fmt"
2020-07-26 17:09:05 +08:00
"net"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/internal/health"
"google.golang.org/grpc"
"google.golang.org/grpc/health/grpc_health_v1"
2020-07-26 17:09:05 +08:00
)
const probeNamePrefix = "zrpc"
2020-07-26 17:09:05 +08:00
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 {
health bool
2020-07-26 17:09:05 +08:00
}
rpcServer struct {
*baseRpcServer
name string
healthManager health.Probe
2020-07-26 17:09:05 +08:00
}
)
2021-03-01 23:52:44 +08:00
// NewRpcServer returns a Server.
func NewRpcServer(addr string, opts ...ServerOption) Server {
2020-07-26 17:09:05 +08:00
var options rpcServerOptions
for _, opt := range opts {
opt(&options)
}
return &rpcServer{
baseRpcServer: newBaseRpcServer(addr, &options),
healthManager: health.NewHealthManager(fmt.Sprintf("%s-%s", probeNamePrefix, addr)),
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
}
func (s *rpcServer) Start(register RegisterFn) error {
lis, err := net.Listen("tcp", s.address)
if err != nil {
return err
}
unaryInterceptorOption := grpc.ChainUnaryInterceptor(s.unaryInterceptors...)
streamInterceptorOption := grpc.ChainStreamInterceptor(s.streamInterceptors...)
options := append(s.options, unaryInterceptorOption, streamInterceptorOption)
2020-07-26 17:09:05 +08:00
server := grpc.NewServer(options...)
register(server)
// register the health check service
if s.health != nil {
grpc_health_v1.RegisterHealthServer(server, s.health)
s.health.Resume()
}
s.healthManager.MarkReady()
health.AddProbe(s.healthManager)
// 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
waitForCalled := proc.AddShutdownListener(func() {
if s.health != nil {
s.health.Shutdown()
}
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
}
// WithRpcHealth returns a func that sets rpc health switch to a Server.
func WithRpcHealth(health bool) ServerOption {
return func(options *rpcServerOptions) {
options.health = health
}
}