This commit is contained in:
2025-06-25 00:01:48 +08:00
parent 3d53c9ec59
commit 53106465ed
30 changed files with 2108 additions and 6 deletions

View File

@@ -0,0 +1,24 @@
package service
import (
"common/discover"
"common/discover/common"
"common/discover/service/game/game_pb"
)
func GatewayNewClient(sid ...string) (game_pb.GameClient, error) {
c, err := discover.FindServer(common.KeyDiscoverGateway, sid...)
if err != nil {
return nil, err
}
return game_pb.NewGameClient(c), nil
}
func GatewayNewBroadcastClient() map[string]game_pb.GameClient {
clientM := make(map[string]game_pb.GameClient)
connM := discover.FindServerAll(common.KeyDiscoverGateway)
for sid, conn := range connM {
clientM[sid] = game_pb.NewGameClient(conn)
}
return clientM
}

View File

@@ -0,0 +1,94 @@
package service
import (
"common/discover"
"common/discover/common"
"common/log"
"common/utils"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"os"
"strconv"
"sync"
"time"
)
type IService interface {
Init(addr string)
Close()
}
type ServiceBase struct {
Target string
SID string
Serve *grpc.Server
EtcdTTL int64
OnInit func(serve *grpc.Server)
OnClose func()
wg *sync.WaitGroup
}
func (s *ServiceBase) Init(addr string) {
s.wg = &sync.WaitGroup{}
s.wg.Add(1)
s.SID = utils.SnowflakeInstance().Generate().String()
go func() {
defer s.wg.Done()
defer s.OnClose()
defer discover.UnRegisterGrpcServer(s.SID)
pMin, _ := strconv.ParseInt(os.Getenv("P_MIN"), 10, 64)
pMax, _ := strconv.ParseInt(os.Getenv("P_MAX"), 10, 64)
if pMin == 0 || pMax == 0 || pMin > pMax {
log.Errorf(" %v init err: pMin or pMax is 0 or pMin > pMax", s.Target)
return
}
// 服务注册
lis, port, err := common.ListenRandomPort(pMin, pMax)
if lis == nil {
log.Errorf(" %v ListenRandomPort err: %v", s.Target, err)
return
}
s.Serve = grpc.NewServer(
grpc.UnaryInterceptor(
func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer func() {
if r := recover(); r != nil {
log.Errorf("server Panic: %v", r)
}
}()
resp, err = handler(ctx, req)
return
},
),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 20 * time.Second,
PermitWithoutStream: true,
}),
)
s.OnInit(s.Serve)
// 服务注册
if err = discover.RegisterGrpcServer(s.Target, s.SID, fmt.Sprintf("%v:%d", addr, port), s.EtcdTTL); err != nil {
log.Errorf("%v RegisterGrpcServer err: %v", s.Target, err)
return
}
if err = s.Serve.Serve(lis); err != nil {
log.Errorf(" %v Serve err: %v", s.Target, err)
return
}
log.Infof("%v server stop.", s.Target)
}()
}
func (s *ServiceBase) Close() {
if s.Serve != nil {
s.Serve.Stop()
s.wg.Wait()
}
}