feat 默认模块

This commit is contained in:
2026-01-20 12:07:18 +08:00
parent a47557920c
commit 1edebb439c
10 changed files with 98 additions and 33 deletions

View File

@@ -9,12 +9,23 @@ import (
"time"
)
const serviceConfig = `{
"loadBalancingConfig": [
{
"round_robin": {}
}
],
"healthCheckConfig": {
"serviceName": ""
}
}`
func NewGrpcConnection(target string) (*grpc.ClientConn, error) {
cc, err := grpc.NewClient(
target,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin": {}}]}`),
grpc.WithDefaultServiceConfig(serviceConfig),
grpc.WithKeepaliveParams(
keepalive.ClientParameters{
Time: 30 * time.Second, // 保活探测包发送的时间间隔

View File

@@ -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()
}
}