feat 默认模块
This commit is contained in:
@@ -8,6 +8,8 @@ import (
|
||||
"git.hlsq.asia/mmorpg/service-common/utils"
|
||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/health"
|
||||
"google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
"net"
|
||||
"sync"
|
||||
@@ -15,7 +17,8 @@ import (
|
||||
)
|
||||
|
||||
type IService interface {
|
||||
Init()
|
||||
Init(ready *sync.WaitGroup)
|
||||
SetReady()
|
||||
Close()
|
||||
}
|
||||
|
||||
@@ -29,10 +32,11 @@ type Base struct {
|
||||
OnInit func(serve *grpc.Server)
|
||||
OnClose func()
|
||||
|
||||
wg *sync.WaitGroup
|
||||
wg *sync.WaitGroup
|
||||
healthcheck *health.Server
|
||||
}
|
||||
|
||||
func (s *Base) Init() {
|
||||
func (s *Base) Init(ready *sync.WaitGroup) {
|
||||
s.wg = &sync.WaitGroup{}
|
||||
s.wg.Add(1)
|
||||
s.SID = utils.SnowflakeInstance().Generate().String()
|
||||
@@ -63,11 +67,18 @@ func (s *Base) Init() {
|
||||
s.Serve = grpc.NewServer(options...)
|
||||
s.OnInit(s.Serve)
|
||||
|
||||
// 健康检查
|
||||
s.healthcheck = health.NewServer()
|
||||
s.healthcheck.SetServingStatus("", grpc_health_v1.HealthCheckResponse_NOT_SERVING)
|
||||
grpc_health_v1.RegisterHealthServer(s.Serve, s.healthcheck)
|
||||
|
||||
// 服务注册
|
||||
if err = discover.RegisterGrpcServer(s.Target, s.SID, fmt.Sprintf("%v:%d", s.Cfg.Address, s.Cfg.Port), s.Cfg.TTL); err != nil {
|
||||
log.Errorf("%v RegisterGrpcServer err: %v", s.Target, err)
|
||||
return
|
||||
}
|
||||
// 准备好了
|
||||
ready.Done()
|
||||
if err = s.Serve.Serve(lis); err != nil {
|
||||
log.Errorf("%v Serve err: %v", s.Target, err)
|
||||
return
|
||||
@@ -76,9 +87,18 @@ func (s *Base) Init() {
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Base) SetReady() {
|
||||
if s.healthcheck != nil {
|
||||
s.healthcheck.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Base) Close() {
|
||||
if s.healthcheck != nil {
|
||||
s.healthcheck.SetServingStatus("", grpc_health_v1.HealthCheckResponse_NOT_SERVING)
|
||||
}
|
||||
if s.Serve != nil {
|
||||
s.Serve.Stop()
|
||||
s.Serve.GracefulStop()
|
||||
s.wg.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user