将游戏服务器uid与sdk分离
This commit is contained in:
1 parent
6d7e4867f5
commit
ddb55671b5
31 files changed
+457
-296
No files matched your search
@@ -16,5 +16,8 @@ mode = "CONSOLE"
|
||||
track = true
|
||||
max_size = 10485760
|
||||
|
||||
[database]
|
||||
url = "mongodb://mongo:27017"
|
||||
|
||||
[mq]
|
||||
nats_url = "nats://nats:4222"
|
||||
@@ -4,5 +4,8 @@ mode = "CONSOLE"
|
||||
track = true
|
||||
max_size = 10485760
|
||||
|
||||
[database]
|
||||
url = "mongodb://mongo:27017"
|
||||
|
||||
[mq]
|
||||
nats_url = "nats://nats:4222"
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"os"
|
||||
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/random"
|
||||
)
|
||||
|
||||
func LoadRegionRsaKey() (signRsaKey []byte, encRsaKeyMap map[string][]byte, pwdRsaKey []byte) {
|
||||
@@ -30,7 +29,3 @@ func LoadRegionRsaKey() (signRsaKey []byte, encRsaKeyMap map[string][]byte, pwdR
|
||||
}
|
||||
return signRsaKey, encRsaKeyMap, pwdRsaKey
|
||||
}
|
||||
|
||||
func LoadRegionEc2b() *random.Ec2b {
|
||||
return random.NewEc2b()
|
||||
}
|
||||
+4
-1
@@ -65,7 +65,10 @@ func Run(ctx context.Context, configFile string) error {
|
||||
messageQueue := mq.NewMessageQueue(api.DISPATCH, APPID, discoveryClient)
|
||||
defer messageQueue.Close()
|
||||
|
||||
db := dao.NewDao()
|
||||
db, err := dao.NewDao()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.CloseDao()
|
||||
|
||||
_ = controller.NewController(db, discoveryClient, messageQueue)
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
dao *dao.Dao
|
||||
db *dao.Dao
|
||||
discovery *rpc.DiscoveryClient
|
||||
signRsaKey []byte
|
||||
encRsaKeyMap map[string][]byte
|
||||
@@ -28,9 +28,9 @@ type Controller struct {
|
||||
messageQueue *mq.MessageQueue
|
||||
}
|
||||
|
||||
func NewController(dao *dao.Dao, discovery *rpc.DiscoveryClient, messageQueue *mq.MessageQueue) (r *Controller) {
|
||||
func NewController(db *dao.Dao, discovery *rpc.DiscoveryClient, messageQueue *mq.MessageQueue) (r *Controller) {
|
||||
r = new(Controller)
|
||||
r.dao = dao
|
||||
r.db = db
|
||||
r.discovery = discovery
|
||||
r.signRsaKey, r.encRsaKeyMap, r.pwdRsaKey = region.LoadRegionRsaKey()
|
||||
rsp, err := r.discovery.GetRegionEc2B(context.TODO(), &api.NullMsg{})
|
||||
@@ -168,7 +168,6 @@ func (c *Controller) registerRouter() {
|
||||
}
|
||||
engine.Use(c.authorize())
|
||||
engine.POST("/gate/token/verify", c.gateTokenVerify)
|
||||
engine.POST("/gate/player/info", c.gatePlayerInfo)
|
||||
port := config.GetConfig().HttpPort
|
||||
addr := ":" + strconv.Itoa(int(port))
|
||||
err := engine.Run(addr)
|
||||
|
||||
@@ -77,7 +77,7 @@ func GetRegionList(ec2b *random.Ec2b) *proto.QueryRegionListHttpRsp {
|
||||
RegionConfig: "pm|fk|add",
|
||||
DownloadMode: 0,
|
||||
DebugMenu: true,
|
||||
DebugLogSwitch: []int32{0, 1, 2},
|
||||
DebugLogSwitch: []int32{0},
|
||||
DebugLog: true,
|
||||
})
|
||||
endec.Xor(clientCustomConfig, dispatchXorKey)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/dispatch/model"
|
||||
"hk4e/pkg/logger"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -65,7 +64,7 @@ func (c *Controller) gateTokenVerify(ctx *gin.Context) {
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
account, err := c.dao.QueryAccountByField("AccountID", uint64(accountId))
|
||||
account, err := c.db.QueryAccountByField("account_id", uint64(accountId))
|
||||
if err != nil || account == nil {
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
@@ -100,86 +99,3 @@ func (c *Controller) gateTokenVerify(ctx *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type PlayerInfoReq struct {
|
||||
AccountId string `json:"accountId"`
|
||||
}
|
||||
|
||||
type PlayerInfoRsp struct {
|
||||
RetCode int32 `json:"retcode"`
|
||||
Message string `json:"message"`
|
||||
Data struct{} `json:"data"`
|
||||
Forbid bool `json:"forbid"`
|
||||
ForbidEndTime uint32 `json:"forbidEndTime"`
|
||||
PlayerID uint32 `json:"playerID"`
|
||||
}
|
||||
|
||||
func (c *Controller) gatePlayerInfo(ctx *gin.Context) {
|
||||
playerInfoReq := new(PlayerInfoReq)
|
||||
err := ctx.ShouldBindJSON(playerInfoReq)
|
||||
if err != nil {
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
logger.Info("gate player info, req: %v", playerInfoReq)
|
||||
accountId, err := strconv.Atoi(playerInfoReq.AccountId)
|
||||
if err != nil {
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
account, err := c.dao.QueryAccountByField("AccountID", uint64(accountId))
|
||||
if err != nil {
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
if account == nil {
|
||||
// 外部sdk登录
|
||||
redisAccountId, err := c.dao.GetAccountId()
|
||||
if err != nil {
|
||||
logger.Error("get account id error: %v", err)
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
if uint32(accountId) > redisAccountId {
|
||||
// 临时修正自增id
|
||||
err := c.dao.SetAccountId(uint32(accountId))
|
||||
if err != nil {
|
||||
logger.Error("set account id error: %v", err)
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
}
|
||||
// 补账号记录
|
||||
playerID, err := c.dao.GetNextYuanShenUid()
|
||||
if err != nil {
|
||||
logger.Error("get next player id error: %v", err)
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
regAccount := &model.Account{
|
||||
AccountID: uint32(accountId),
|
||||
Username: "",
|
||||
Password: "",
|
||||
PlayerID: playerID,
|
||||
Token: "",
|
||||
ComboToken: "",
|
||||
Forbid: false,
|
||||
ForbidEndTime: 0,
|
||||
}
|
||||
_, err = c.dao.InsertAccount(regAccount)
|
||||
if err != nil {
|
||||
logger.Error("insert account error: %v", err)
|
||||
c.gateReqErrorRsp(ctx)
|
||||
return
|
||||
}
|
||||
account = regAccount
|
||||
}
|
||||
ctx.JSON(http.StatusOK, &PlayerInfoRsp{
|
||||
RetCode: 0,
|
||||
Message: "OK",
|
||||
Data: struct{}{},
|
||||
Forbid: account.Forbid,
|
||||
ForbidEndTime: account.ForbidEndTime,
|
||||
PlayerID: account.PlayerID,
|
||||
})
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func (c *Controller) log8888(ctx *gin.Context) {
|
||||
logger.Error("parse client log error: %v", err)
|
||||
return
|
||||
}
|
||||
_, err = c.dao.InsertClientLog(clientLog)
|
||||
_, err = c.db.InsertClientLog(clientLog)
|
||||
if err != nil {
|
||||
logger.Error("insert client log error: %v", err)
|
||||
return
|
||||
|
||||
@@ -92,14 +92,14 @@ func (c *Controller) apiLogin(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
account, err := c.dao.QueryAccountByField("Username", username)
|
||||
account, err := c.db.QueryAccountByField("username", username)
|
||||
if err != nil {
|
||||
logger.Error("query account from db error: %v", err)
|
||||
return
|
||||
}
|
||||
if account == nil {
|
||||
// 自动注册
|
||||
accountId, err := c.dao.GetNextAccountId()
|
||||
accountId, err := c.db.GetNextAccountId()
|
||||
if err != nil {
|
||||
logger.Error("get next account id error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
@@ -107,29 +107,18 @@ func (c *Controller) apiLogin(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
playerID, err := c.dao.GetNextYuanShenUid()
|
||||
if err != nil {
|
||||
logger.Error("get next player id error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "服务器内部错误:-2"
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
regAccount := &model.Account{
|
||||
AccountID: accountId,
|
||||
Username: username,
|
||||
Password: endec.Md5Str(password),
|
||||
PlayerID: playerID,
|
||||
Token: "",
|
||||
ComboToken: "",
|
||||
Forbid: false,
|
||||
ForbidEndTime: 0,
|
||||
AccountId: accountId,
|
||||
Username: username,
|
||||
Password: endec.Md5Str(password),
|
||||
Token: "",
|
||||
ComboToken: "",
|
||||
}
|
||||
_, err = c.dao.InsertAccount(regAccount)
|
||||
_, err = c.db.InsertAccount(regAccount)
|
||||
if err != nil {
|
||||
logger.Error("insert account error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "服务器内部错误:-3"
|
||||
responseData.Message = "服务器内部错误:-2"
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
@@ -143,24 +132,24 @@ func (c *Controller) apiLogin(ctx *gin.Context) {
|
||||
}
|
||||
// 生成新的token
|
||||
account.Token = base64.StdEncoding.EncodeToString(random.GetRandomByte(24))
|
||||
_, err = c.dao.UpdateAccountFieldByFieldName("AccountID", account.AccountID, "Token", account.Token)
|
||||
_, err = c.db.UpdateAccountFieldByFieldName("account_id", account.AccountId, "token", account.Token)
|
||||
if err != nil {
|
||||
logger.Error("update account token error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "服务器内部错误:-3"
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
_, err = c.db.UpdateAccountFieldByFieldName("account_id", account.AccountId, "token_create_time", time.Now().UnixMilli())
|
||||
if err != nil {
|
||||
logger.Error("update account token time error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "服务器内部错误:-4"
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
_, err = c.dao.UpdateAccountFieldByFieldName("AccountID", account.AccountID, "TokenCreateTime", time.Now().UnixMilli())
|
||||
if err != nil {
|
||||
logger.Error("update account token time error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "服务器内部错误:-5"
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
responseData.Message = "OK"
|
||||
responseData.Data.Account.Uid = strconv.FormatInt(int64(account.AccountID), 10)
|
||||
responseData.Data.Account.Uid = strconv.FormatInt(int64(account.AccountId), 10)
|
||||
responseData.Data.Account.Token = account.Token
|
||||
responseData.Data.Account.Email = account.Username
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
@@ -178,7 +167,7 @@ func (c *Controller) apiVerify(ctx *gin.Context) {
|
||||
logger.Error("parse uid error: %v", err)
|
||||
return
|
||||
}
|
||||
account, err := c.dao.QueryAccountByField("AccountID", uid)
|
||||
account, err := c.db.QueryAccountByField("account_id", uid)
|
||||
if err != nil {
|
||||
logger.Error("query account from db error: %v", err)
|
||||
return
|
||||
@@ -227,7 +216,7 @@ func (c *Controller) v2Login(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
responseData := api.NewComboTokenRsp()
|
||||
account, err := c.dao.QueryAccountByField("AccountID", uid)
|
||||
account, err := c.db.QueryAccountByField("account_id", uid)
|
||||
if account == nil || account.Token != loginData.Token {
|
||||
responseData.Retcode = -201
|
||||
responseData.Message = "token错误"
|
||||
@@ -236,7 +225,7 @@ func (c *Controller) v2Login(ctx *gin.Context) {
|
||||
}
|
||||
// 生成新的comboToken
|
||||
account.ComboToken = random.GetRandomByteHexStr(20)
|
||||
_, err = c.dao.UpdateAccountFieldByFieldName("AccountID", account.AccountID, "ComboToken", account.ComboToken)
|
||||
_, err = c.db.UpdateAccountFieldByFieldName("account_id", account.AccountId, "combo_token", account.ComboToken)
|
||||
if err != nil {
|
||||
logger.Error("update combo token error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
@@ -244,7 +233,7 @@ func (c *Controller) v2Login(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, responseData)
|
||||
return
|
||||
}
|
||||
_, err = c.dao.UpdateAccountFieldByFieldName("AccountID", account.AccountID, "ComboTokenCreateTime", time.Now().UnixMilli())
|
||||
_, err = c.db.UpdateAccountFieldByFieldName("account_id", account.AccountId, "combo_token_create_time", time.Now().UnixMilli())
|
||||
if err != nil {
|
||||
logger.Error("update combo token time error: %v", err)
|
||||
responseData.Retcode = -201
|
||||
|
||||
@@ -8,10 +8,8 @@ import (
|
||||
const RedisPlayerKeyPrefix = "HK4E"
|
||||
|
||||
const (
|
||||
AccountIdRedisKey = "AccountId"
|
||||
AccountIdBegin uint32 = 10000
|
||||
YuanShenUidRedisKey = "YuanShenUid"
|
||||
YuanShenUidBegin uint32 = 100000000
|
||||
AccountIdRedisKey = "AccountId"
|
||||
AccountIdBegin uint32 = 10000
|
||||
)
|
||||
|
||||
func (d *Dao) GetNextAccountId() (uint32, error) {
|
||||
@@ -26,10 +24,6 @@ func (d *Dao) SetAccountId(accountId uint32) error {
|
||||
return d.redisSet(RedisPlayerKeyPrefix+":"+AccountIdRedisKey, accountId)
|
||||
}
|
||||
|
||||
func (d *Dao) GetNextYuanShenUid() (uint32, error) {
|
||||
return d.redisInc(RedisPlayerKeyPrefix + ":" + YuanShenUidRedisKey)
|
||||
}
|
||||
|
||||
func (d *Dao) redisInc(keyName string) (uint32, error) {
|
||||
var exist int64 = 0
|
||||
var err error = nil
|
||||
@@ -42,17 +36,11 @@ func (d *Dao) redisInc(keyName string) (uint32, error) {
|
||||
return 0, err
|
||||
}
|
||||
if exist == 0 {
|
||||
var value uint32 = 0
|
||||
if keyName == RedisPlayerKeyPrefix+":"+AccountIdRedisKey {
|
||||
value = AccountIdBegin
|
||||
} else if keyName == RedisPlayerKeyPrefix+":"+YuanShenUidRedisKey {
|
||||
value = YuanShenUidBegin
|
||||
}
|
||||
var err error = nil
|
||||
if d.redisCluster != nil {
|
||||
err = d.redisCluster.Set(context.TODO(), keyName, value, 0).Err()
|
||||
err = d.redisCluster.Set(context.TODO(), keyName, AccountIdBegin, 0).Err()
|
||||
} else {
|
||||
err = d.redis.Set(context.TODO(), keyName, value, 0).Err()
|
||||
err = d.redis.Set(context.TODO(), keyName, AccountIdBegin, 0).Err()
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
+6
-6
@@ -20,19 +20,19 @@ type Dao struct {
|
||||
redisCluster *redis.ClusterClient
|
||||
}
|
||||
|
||||
func NewDao() (r *Dao) {
|
||||
r = new(Dao)
|
||||
func NewDao() (*Dao, error) {
|
||||
r := new(Dao)
|
||||
|
||||
clientOptions := options.Client().ApplyURI(config.GetConfig().Database.Url).SetMinPoolSize(10).SetMaxPoolSize(100)
|
||||
client, err := mongo.Connect(context.TODO(), clientOptions)
|
||||
if err != nil {
|
||||
logger.Error("mongo connect error: %v", err)
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
err = client.Ping(context.TODO(), readpref.Primary())
|
||||
if err != nil {
|
||||
logger.Error("mongo ping error: %v", err)
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
r.mongo = client
|
||||
r.db = client.Database("dispatch_hk4e")
|
||||
@@ -64,10 +64,10 @@ func NewDao() (r *Dao) {
|
||||
}
|
||||
if err != nil {
|
||||
logger.Error("redis ping error: %v", err)
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return r
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (d *Dao) CloseDao() {
|
||||
|
||||
@@ -4,14 +4,11 @@ import "go.mongodb.org/mongo-driver/bson/primitive"
|
||||
|
||||
type Account struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty"`
|
||||
AccountID uint32 `bson:"AccountID"`
|
||||
PlayerID uint32 `bson:"PlayerID"`
|
||||
Username string `bson:"Username"`
|
||||
Password string `bson:"Password"`
|
||||
Token string `bson:"Token"`
|
||||
TokenCreateTime uint64 `bson:"TokenCreateTime"` // 毫秒时间戳
|
||||
ComboToken string `bson:"ComboToken"`
|
||||
ComboTokenCreateTime uint64 `bson:"ComboTokenCreateTime"` // 毫秒时间戳
|
||||
Forbid bool `bson:"Forbid"`
|
||||
ForbidEndTime uint32 `bson:"ForbidEndTime"` // 秒时间戳
|
||||
AccountId uint32 `bson:"account_id"` // 账号id
|
||||
Username string `bson:"username"` // 用户名
|
||||
Password string `bson:"password"` // 密码
|
||||
Token string `bson:"token"` // 账号token
|
||||
TokenCreateTime uint64 `bson:"token_create_time"` // 毫秒时间戳
|
||||
ComboToken string `bson:"combo_token"` // 游戏服务器token
|
||||
ComboTokenCreateTime uint64 `bson:"combo_token_create_time"` // 毫秒时间戳
|
||||
}
|
||||
@@ -9,37 +9,12 @@ type Service struct {
|
||||
}
|
||||
|
||||
// UserPasswordChange 用户密码改变
|
||||
func (s *Service) UserPasswordChange(uid uint32) bool {
|
||||
func (s *Service) UserPasswordChange(accountId uint32) bool {
|
||||
// http登录态失效
|
||||
_, err := s.dao.UpdateAccountFieldByFieldName("PlayerID", uid, "TokenCreateTime", 0)
|
||||
_, err := s.dao.UpdateAccountFieldByFieldName("account_id", accountId, "token_create_time", 0)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// TODO 游戏内登录态失效
|
||||
return true
|
||||
}
|
||||
|
||||
// ForbidUser 封号
|
||||
func (s *Service) ForbidUser(uid uint32, forbidEndTime uint64) bool {
|
||||
// 写入账号封禁信息
|
||||
_, err := s.dao.UpdateAccountFieldByFieldName("PlayerID", uid, "Forbid", true)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, err = s.dao.UpdateAccountFieldByFieldName("PlayerID", uid, "ForbidEndTime", forbidEndTime)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// TODO 游戏强制下线
|
||||
return true
|
||||
}
|
||||
|
||||
// UnForbidUser 解封
|
||||
func (s *Service) UnForbidUser(uid uint32) bool {
|
||||
// 解除账号封禁
|
||||
_, err := s.dao.UpdateAccountFieldByFieldName("PlayerID", uid, "Forbid", false)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -35,15 +35,21 @@ sleep 5
|
||||
|
||||
echo "init hk4e database table"
|
||||
mongo --host "${IP}" --port 27117 <<EOF
|
||||
sh.enableSharding("node_hk4e")
|
||||
sh.shardCollection("node_hk4e.region", {"region_id": "hashed"})
|
||||
sh.enableBalancing("node_hk4e.region")
|
||||
sh.enableSharding("dispatch_hk4e")
|
||||
sh.shardCollection("dispatch_hk4e.account", {"AccountID": "hashed"})
|
||||
sh.shardCollection("dispatch_hk4e.account", {"account_id": "hashed"})
|
||||
sh.enableBalancing("dispatch_hk4e.account")
|
||||
sh.shardCollection("dispatch_hk4e.client_log", {"_id": "hashed"})
|
||||
sh.enableBalancing("dispatch_hk4e.client_log")
|
||||
sh.enableSharding("gate_hk4e")
|
||||
sh.shardCollection("gate_hk4e.account", {"open_id": "hashed"})
|
||||
sh.enableBalancing("gate_hk4e.account")
|
||||
sh.enableSharding("gs_hk4e")
|
||||
sh.shardCollection("gs_hk4e.player", {"PlayerID": "hashed"})
|
||||
sh.shardCollection("gs_hk4e.player", {"player_id": "hashed"})
|
||||
sh.enableBalancing("gs_hk4e.player")
|
||||
sh.shardCollection("gs_hk4e.chat_msg", {"Uid": "hashed"})
|
||||
sh.shardCollection("gs_hk4e.chat_msg", {"uid": "hashed"})
|
||||
sh.enableBalancing("gs_hk4e.chat_msg")
|
||||
sh.startBalancer()
|
||||
db.adminCommand("flushRouterConfig")
|
||||
|
||||
+8
-1
@@ -13,6 +13,7 @@ import (
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/rpc"
|
||||
"hk4e/gate/dao"
|
||||
"hk4e/gate/net"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/logger"
|
||||
@@ -74,7 +75,13 @@ func Run(ctx context.Context, configFile string) error {
|
||||
messageQueue := mq.NewMessageQueue(api.GATE, APPID, discoveryClient)
|
||||
defer messageQueue.Close()
|
||||
|
||||
kcpConnManager := net.NewKcpConnManager(messageQueue, discoveryClient)
|
||||
db, err := dao.NewDao()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.CloseDao()
|
||||
|
||||
kcpConnManager := net.NewKcpConnManager(db, messageQueue, discoveryClient)
|
||||
defer kcpConnManager.Close()
|
||||
|
||||
c := make(chan os.Signal, 1)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hk4e/pkg/logger"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
type Account struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty"`
|
||||
OpenId string `bson:"open_id"`
|
||||
Uid uint32 `bson:"uid"`
|
||||
IsForbid bool `bson:"is_forbid"`
|
||||
ForbidEndTime uint32 `bson:"forbid_end_time"`
|
||||
}
|
||||
|
||||
func (d *Dao) InsertAccount(account *Account) (primitive.ObjectID, error) {
|
||||
db := d.db.Collection("account")
|
||||
id, err := db.InsertOne(context.TODO(), account)
|
||||
if err != nil {
|
||||
return primitive.ObjectID{}, err
|
||||
} else {
|
||||
_id, ok := id.InsertedID.(primitive.ObjectID)
|
||||
if !ok {
|
||||
logger.Error("get insert id error")
|
||||
return primitive.ObjectID{}, nil
|
||||
}
|
||||
return _id, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Dao) QueryAccountByOpenId(openId string) (*Account, error) {
|
||||
db := d.db.Collection("account")
|
||||
result := db.FindOne(
|
||||
context.TODO(),
|
||||
bson.D{{"open_id", openId}},
|
||||
)
|
||||
account := new(Account)
|
||||
err := result.Decode(account)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/pkg/logger"
|
||||
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||
)
|
||||
|
||||
type Dao struct {
|
||||
mongo *mongo.Client
|
||||
db *mongo.Database
|
||||
}
|
||||
|
||||
func NewDao() (*Dao, error) {
|
||||
r := new(Dao)
|
||||
|
||||
clientOptions := options.Client().ApplyURI(config.GetConfig().Database.Url).SetMinPoolSize(10).SetMaxPoolSize(100)
|
||||
client, err := mongo.Connect(context.TODO(), clientOptions)
|
||||
if err != nil {
|
||||
logger.Error("mongo connect error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
err = client.Ping(context.TODO(), readpref.Primary())
|
||||
if err != nil {
|
||||
logger.Error("mongo ping error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
r.mongo = client
|
||||
r.db = client.Database("gate_hk4e")
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (d *Dao) CloseDao() {
|
||||
err := d.mongo.Disconnect(context.TODO())
|
||||
if err != nil {
|
||||
logger.Error("mongo close error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"hk4e/common/region"
|
||||
"hk4e/common/rpc"
|
||||
"hk4e/gate/client_proto"
|
||||
"hk4e/gate/dao"
|
||||
"hk4e/gate/kcp"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/logger"
|
||||
@@ -49,6 +50,7 @@ type KcpEvent struct {
|
||||
}
|
||||
|
||||
type KcpConnManager struct {
|
||||
db *dao.Dao
|
||||
discovery *rpc.DiscoveryClient // 节点服务器rpc客户端
|
||||
messageQueue *mq.MessageQueue // 消息队列
|
||||
globalGsOnlineMap map[uint32]string // 全服玩家在线表
|
||||
@@ -72,8 +74,9 @@ type KcpConnManager struct {
|
||||
dispatchKey []byte
|
||||
}
|
||||
|
||||
func NewKcpConnManager(messageQueue *mq.MessageQueue, discovery *rpc.DiscoveryClient) (r *KcpConnManager) {
|
||||
func NewKcpConnManager(db *dao.Dao, messageQueue *mq.MessageQueue, discovery *rpc.DiscoveryClient) (r *KcpConnManager) {
|
||||
r = new(KcpConnManager)
|
||||
r.db = db
|
||||
r.discovery = discovery
|
||||
r.messageQueue = messageQueue
|
||||
r.globalGsOnlineMap = make(map[uint32]string)
|
||||
|
||||
+36
-40
@@ -17,6 +17,7 @@ import (
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/dispatch/controller"
|
||||
"hk4e/gate/dao"
|
||||
"hk4e/gate/kcp"
|
||||
"hk4e/node/api"
|
||||
"hk4e/pkg/endec"
|
||||
@@ -454,10 +455,6 @@ type RemoteKick struct {
|
||||
kickFinishNotifyChan chan bool
|
||||
}
|
||||
|
||||
func (k *KcpConnManager) loginFailClose(session *Session) {
|
||||
k.forceCloseKcpConn(session.sessionId, kcp.EnetLoginUnfinished)
|
||||
}
|
||||
|
||||
func (k *KcpConnManager) loginFailRsp(uid uint32, retCode proto.Retcode, isForbid bool, forbidEndTime uint32) *proto.GetPlayerTokenRsp {
|
||||
rsp := new(proto.GetPlayerTokenRsp)
|
||||
rsp.Uid = uid
|
||||
@@ -490,38 +487,49 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
|
||||
Region: "",
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("verify token error: %v, account uid: %v", err, req.AccountUid)
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
logger.Error("verify token http error: %v, openId: %v", err, req.AccountUid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
}
|
||||
if tokenVerifyRsp.RetCode != 0 {
|
||||
logger.Error("token error, account id: %v", req.AccountUid)
|
||||
logger.Error("verify token error, openId: %v", req.AccountUid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_TOKEN_ERROR, false, 0)
|
||||
}
|
||||
// 查询玩家账号信息
|
||||
playerInfoRsp, err := httpclient.PostJson[controller.PlayerInfoRsp](
|
||||
config.GetConfig().Hk4e.LoginSdkUrl+"/gate/player/info",
|
||||
&controller.PlayerInfoReq{
|
||||
AccountId: req.AccountUid,
|
||||
})
|
||||
account, err := k.db.QueryAccountByOpenId(req.AccountUid)
|
||||
if err != nil {
|
||||
logger.Error("query player info error: %v, account uid: %v", err, req.AccountUid)
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
logger.Error("query account error: %v, openId: %v", err, req.AccountUid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_LOGIN_DB_FAIL, false, 0)
|
||||
}
|
||||
uid := playerInfoRsp.PlayerID
|
||||
if playerInfoRsp.Forbid {
|
||||
// 封号通知
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_BLACK_UID, true, playerInfoRsp.ForbidEndTime)
|
||||
if account == nil {
|
||||
// 注册账号与uid关联
|
||||
getNextUidRsp, err := k.discovery.GetNextUid(context.TODO(), &api.NullMsg{})
|
||||
if err != nil {
|
||||
logger.Error("get next uid error: %v, openId: %v", err, req.AccountUid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
}
|
||||
account = &dao.Account{
|
||||
OpenId: req.AccountUid,
|
||||
Uid: getNextUidRsp.Uid,
|
||||
IsForbid: false,
|
||||
ForbidEndTime: 0,
|
||||
}
|
||||
_, err = k.db.InsertAccount(account)
|
||||
if err != nil {
|
||||
logger.Error("insert account error: %v, openId: %v", err, req.AccountUid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_LOGIN_DB_FAIL, false, 0)
|
||||
}
|
||||
}
|
||||
uid := account.Uid
|
||||
if account.IsForbid {
|
||||
// 封号
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_BLACK_UID, true, account.ForbidEndTime)
|
||||
}
|
||||
addr := session.conn.RemoteAddr()
|
||||
addrSplit := strings.Split(addr, ":")
|
||||
clientIp := addrSplit[0]
|
||||
stopServerInfo, err := k.discovery.GetStopServerInfo(context.TODO(), &api.GetStopServerInfoReq{ClientIpAddr: clientIp})
|
||||
if err != nil {
|
||||
logger.Error("get stop server info error: %v", err)
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
logger.Error("get stop server info error: %v, uid: %v", err, uid)
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
}
|
||||
if stopServerInfo.StopServer {
|
||||
return k.loginFailRsp(uid, proto.Retcode_RET_STOP_SERVER, false, 0)
|
||||
@@ -550,8 +558,7 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
|
||||
case <-timer.C:
|
||||
logger.Error("global interrupt login reg wait timeout, uid: %v", uid)
|
||||
timer.Stop()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
case <-regFinishNotifyChan:
|
||||
timer.Stop()
|
||||
}
|
||||
@@ -577,8 +584,7 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
|
||||
case <-timer.C:
|
||||
logger.Error("global interrupt login kick wait timeout, uid: %v", uid)
|
||||
timer.Stop()
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
case <-kickFinishNotifyChan:
|
||||
timer.Stop()
|
||||
}
|
||||
@@ -593,8 +599,7 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("get gs server appid error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return nil
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
}
|
||||
session.gsServerAppId = gsServerAppId.AppId
|
||||
anticheatServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
|
||||
@@ -622,7 +627,7 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
|
||||
ok := k.keyExchange(session, uid, rsp)
|
||||
if !ok {
|
||||
logger.Error("key exchange error, uid: %v", uid)
|
||||
return nil
|
||||
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
|
||||
}
|
||||
return rsp
|
||||
}
|
||||
@@ -657,39 +662,33 @@ func (k *KcpConnManager) keyExchange(session *Session, uid uint32, rsp *proto.Ge
|
||||
encPubPrivKey, exist := k.encRsaKeyMap[keyId]
|
||||
if !exist {
|
||||
logger.Error("can not found key id: %v, uid: %v", keyId, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
pubKey, err := endec.RsaParsePubKeyByPrivKey(encPubPrivKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa pub key error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
signPrivkey, err := endec.RsaParsePrivKey(k.signRsaKey)
|
||||
if err != nil {
|
||||
logger.Error("parse rsa priv key error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeedBase64 := session.clientRandKey
|
||||
clientSeedEnc, err := base64.StdEncoding.DecodeString(clientSeedBase64)
|
||||
if err != nil {
|
||||
logger.Error("parse client seed base64 error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeed, err := endec.RsaDecrypt(clientSeedEnc, signPrivkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa dec error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
clientSeedUint64 := uint64(0)
|
||||
err = binary.Read(bytes.NewReader(clientSeed), binary.BigEndian, &clientSeedUint64)
|
||||
if err != nil {
|
||||
logger.Error("parse client seed to uint64 error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
logger.Debug("clientSeed: %v, clientSeedUint64: %v", clientSeed, clientSeedUint64)
|
||||
@@ -699,7 +698,6 @@ func (k *KcpConnManager) keyExchange(session *Session, uid uint32, rsp *proto.Ge
|
||||
err = binary.Write(seedBuf, binary.BigEndian, seedUint64)
|
||||
if err != nil {
|
||||
logger.Error("write seed uint64 to bytes error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
seed := seedBuf.Bytes()
|
||||
@@ -707,13 +705,11 @@ func (k *KcpConnManager) keyExchange(session *Session, uid uint32, rsp *proto.Ge
|
||||
seedEnc, err := endec.RsaEncrypt(seed, pubKey)
|
||||
if err != nil {
|
||||
logger.Error("rsa enc error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
seedSign, err := endec.RsaSign(seed, signPrivkey)
|
||||
if err != nil {
|
||||
logger.Error("rsa sign error: %v, uid: %v", err, uid)
|
||||
k.loginFailClose(session)
|
||||
return false
|
||||
}
|
||||
rsp.KeyId = session.keyId
|
||||
|
||||
+2
-2
@@ -20,8 +20,8 @@ type Dao struct {
|
||||
redisCluster *redis.ClusterClient
|
||||
}
|
||||
|
||||
func NewDao() (r *Dao, err error) {
|
||||
r = new(Dao)
|
||||
func NewDao() (*Dao, error) {
|
||||
r := new(Dao)
|
||||
|
||||
clientOptions := options.Client().ApplyURI(config.GetConfig().Database.Url).SetMinPoolSize(1).SetMaxPoolSize(10)
|
||||
client, err := mongo.Connect(context.TODO(), clientOptions)
|
||||
|
||||
+27
-19
@@ -67,9 +67,9 @@ func (d *Dao) InsertChatMsgList(chatMsgList []*model.ChatMsg) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) DeletePlayer(playerID uint32) error {
|
||||
func (d *Dao) DeletePlayer(playerId uint32) error {
|
||||
db := d.db.Collection("player")
|
||||
_, err := db.DeleteOne(context.TODO(), bson.D{{"PlayerID", playerID}})
|
||||
_, err := db.DeleteOne(context.TODO(), bson.D{{"player_id", playerId}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -85,14 +85,14 @@ func (d *Dao) DeleteChatMsg(id primitive.ObjectID) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) DeletePlayerList(playerIDList []uint32) error {
|
||||
if len(playerIDList) == 0 {
|
||||
func (d *Dao) DeletePlayerList(playerIdList []uint32) error {
|
||||
if len(playerIdList) == 0 {
|
||||
return nil
|
||||
}
|
||||
db := d.db.Collection("player")
|
||||
modelOperateList := make([]mongo.WriteModel, 0)
|
||||
for _, playerID := range playerIDList {
|
||||
modelOperate := mongo.NewDeleteOneModel().SetFilter(bson.D{{"PlayerID", playerID}})
|
||||
for _, playerId := range playerIdList {
|
||||
modelOperate := mongo.NewDeleteOneModel().SetFilter(bson.D{{"player_id", playerId}})
|
||||
modelOperateList = append(modelOperateList, modelOperate)
|
||||
}
|
||||
_, err := db.BulkWrite(context.TODO(), modelOperateList)
|
||||
@@ -123,7 +123,7 @@ func (d *Dao) UpdatePlayer(player *model.Player) error {
|
||||
db := d.db.Collection("player")
|
||||
_, err := db.UpdateMany(
|
||||
context.TODO(),
|
||||
bson.D{{"PlayerID", player.PlayerID}},
|
||||
bson.D{{"player_id", player.PlayerID}},
|
||||
bson.D{{"$set", player}},
|
||||
)
|
||||
if err != nil {
|
||||
@@ -152,7 +152,7 @@ func (d *Dao) UpdatePlayerList(playerList []*model.Player) error {
|
||||
db := d.db.Collection("player")
|
||||
modelOperateList := make([]mongo.WriteModel, 0)
|
||||
for _, player := range playerList {
|
||||
modelOperate := mongo.NewUpdateManyModel().SetFilter(bson.D{{"PlayerID", player.PlayerID}}).SetUpdate(bson.D{{"$set", player}})
|
||||
modelOperate := mongo.NewUpdateManyModel().SetFilter(bson.D{{"player_id", player.PlayerID}}).SetUpdate(bson.D{{"$set", player}})
|
||||
modelOperateList = append(modelOperateList, modelOperate)
|
||||
}
|
||||
_, err := db.BulkWrite(context.TODO(), modelOperateList)
|
||||
@@ -179,21 +179,25 @@ func (d *Dao) UpdateChatMsgList(chatMsgList []*model.ChatMsg) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) QueryPlayerByID(playerID uint32) (*model.Player, error) {
|
||||
func (d *Dao) QueryPlayerById(playerId uint32) (*model.Player, error) {
|
||||
db := d.db.Collection("player")
|
||||
result := db.FindOne(
|
||||
context.TODO(),
|
||||
bson.D{{"PlayerID", playerID}},
|
||||
bson.D{{"player_id", playerId}},
|
||||
)
|
||||
player := new(model.Player)
|
||||
err := result.Decode(player)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return player, nil
|
||||
}
|
||||
|
||||
func (d *Dao) QueryChatMsgByID(id primitive.ObjectID) (*model.ChatMsg, error) {
|
||||
func (d *Dao) QueryChatMsgById(id primitive.ObjectID) (*model.ChatMsg, error) {
|
||||
db := d.db.Collection("chat_msg")
|
||||
result := db.FindOne(
|
||||
context.TODO(),
|
||||
@@ -202,7 +206,11 @@ func (d *Dao) QueryChatMsgByID(id primitive.ObjectID) (*model.ChatMsg, error) {
|
||||
chatMsg := new(model.ChatMsg)
|
||||
err := result.Decode(chatMsg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return chatMsg, nil
|
||||
}
|
||||
@@ -254,9 +262,9 @@ func (d *Dao) QueryChatMsgListByUid(uid uint32) ([]*model.ChatMsg, error) {
|
||||
result := make([]*model.ChatMsg, 0)
|
||||
find, err := db.Find(
|
||||
context.TODO(),
|
||||
bson.D{{"$or", []bson.D{{{"ToUid", uid}}, {{"Uid", uid}}}}},
|
||||
bson.D{{"$or", []bson.D{{{"to_uid", uid}}, {{"uid", uid}}}}},
|
||||
options.Find().SetLimit(MaxQueryChatMsgLen),
|
||||
options.Find().SetSort(bson.M{"Time": 1}),
|
||||
options.Find().SetSort(bson.M{"time": 1}),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -276,16 +284,16 @@ func (d *Dao) ReadAndUpdateChatMsgByUid(uid uint32, targetUid uint32) error {
|
||||
db := d.db.Collection("chat_msg")
|
||||
_, err := db.UpdateMany(
|
||||
context.TODO(),
|
||||
bson.D{{"ToUid", uid}, {"Uid", targetUid}},
|
||||
bson.D{{"$set", bson.D{{"IsRead", true}}}},
|
||||
bson.D{{"to_uid", uid}, {"uid", targetUid}},
|
||||
bson.D{{"$set", bson.D{{"is_read", true}}}},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = db.UpdateMany(
|
||||
context.TODO(),
|
||||
bson.D{{"Uid", uid}, {"ToUid", targetUid}},
|
||||
bson.D{{"$set", bson.D{{"IsRead", true}}}},
|
||||
bson.D{{"uid", uid}, {"to_uid", targetUid}},
|
||||
bson.D{{"$set", bson.D{{"is_read", true}}}},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+4
-4
@@ -46,7 +46,7 @@ var SELF *model.Player
|
||||
|
||||
type Game struct {
|
||||
discovery *rpc.DiscoveryClient // node节点服务器的natsrpc客户端
|
||||
dao *dao.Dao
|
||||
db *dao.Dao
|
||||
snowflake *alg.SnowflakeWorker
|
||||
gsId uint32
|
||||
gsAppid string
|
||||
@@ -55,10 +55,10 @@ type Game struct {
|
||||
isStop bool
|
||||
}
|
||||
|
||||
func NewGameCore(dao *dao.Dao, messageQueue *mq.MessageQueue, gsId uint32, gsAppid string, mainGsAppid string, discovery *rpc.DiscoveryClient) (r *Game) {
|
||||
func NewGameCore(db *dao.Dao, messageQueue *mq.MessageQueue, gsId uint32, gsAppid string, mainGsAppid string, discovery *rpc.DiscoveryClient) (r *Game) {
|
||||
r = new(Game)
|
||||
r.discovery = discovery
|
||||
r.dao = dao
|
||||
r.db = db
|
||||
MESSAGE_QUEUE = messageQueue
|
||||
r.snowflake = alg.NewSnowflakeWorker(int64(gsId))
|
||||
r.gsId = gsId
|
||||
@@ -67,7 +67,7 @@ func NewGameCore(dao *dao.Dao, messageQueue *mq.MessageQueue, gsId uint32, gsApp
|
||||
GAME = r
|
||||
LOCAL_EVENT_MANAGER = NewLocalEventManager()
|
||||
ROUTE_MANAGER = NewRouteManager()
|
||||
USER_MANAGER = NewUserManager(dao)
|
||||
USER_MANAGER = NewUserManager(db)
|
||||
WORLD_MANAGER = NewWorldManager(r.snowflake)
|
||||
TICK_MANAGER = NewTickManager()
|
||||
COMMAND_MANAGER = NewCommandManager()
|
||||
|
||||
@@ -19,16 +19,16 @@ import (
|
||||
// 玩家定时保存 写入db和redis
|
||||
|
||||
type UserManager struct {
|
||||
dao *dao.Dao // db对象
|
||||
db *dao.Dao // db对象
|
||||
playerMap map[uint32]*model.Player // 内存玩家数据
|
||||
saveUserChan chan *SaveUserData // 用于主协程发送玩家数据给定时保存协程
|
||||
remotePlayerMap map[uint32]string // 远程玩家 key:userId value:玩家所在gs的appid
|
||||
remotePlayerMapLock sync.RWMutex
|
||||
}
|
||||
|
||||
func NewUserManager(dao *dao.Dao) (r *UserManager) {
|
||||
func NewUserManager(db *dao.Dao) (r *UserManager) {
|
||||
r = new(UserManager)
|
||||
r.dao = dao
|
||||
r.db = db
|
||||
r.playerMap = make(map[uint32]*model.Player)
|
||||
r.saveUserChan = make(chan *SaveUserData) // 无缓冲区chan 避免主协程在写入时被迫加锁
|
||||
r.remotePlayerMap = make(map[uint32]string)
|
||||
@@ -107,7 +107,7 @@ func (u *UserManager) OnlineUser(userId uint32, clientSeq uint32, gateAppId stri
|
||||
}
|
||||
go func() {
|
||||
// 加离线玩家数据分布式锁
|
||||
ok := u.dao.DistLockSync(userId)
|
||||
ok := u.db.DistLockSync(userId)
|
||||
if !ok {
|
||||
logger.Error("lock redis offline player data error, uid: %v", userId)
|
||||
return
|
||||
@@ -117,7 +117,7 @@ func (u *UserManager) OnlineUser(userId uint32, clientSeq uint32, gateAppId stri
|
||||
u.SaveUserToRedisSync(player)
|
||||
}
|
||||
// 解离线玩家数据分布式锁
|
||||
u.dao.DistUnlock(userId)
|
||||
u.db.DistUnlock(userId)
|
||||
if player != nil {
|
||||
u.ChangeUserDbState(player, model.DbNormal)
|
||||
player.ChatMsgMap = u.LoadUserChatMsgFromDbSync(userId)
|
||||
@@ -342,7 +342,7 @@ func (u *UserManager) LoadTempOfflineUser(userId uint32, lock bool) *model.Playe
|
||||
}
|
||||
if lock {
|
||||
// 加离线玩家数据分布式锁
|
||||
ok := u.dao.DistLockSync(userId)
|
||||
ok := u.db.DistLockSync(userId)
|
||||
if !ok {
|
||||
logger.Error("lock redis offline player data error, uid: %v", userId)
|
||||
return nil
|
||||
@@ -384,13 +384,13 @@ func (u *UserManager) SaveTempOfflineUser(player *model.Player) {
|
||||
if err != nil {
|
||||
logger.Error("marshal player data error: %v", err)
|
||||
// 解离线玩家数据分布式锁
|
||||
u.dao.DistUnlock(player.PlayerID)
|
||||
u.db.DistUnlock(player.PlayerID)
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
// 解离线玩家数据分布式锁
|
||||
u.dao.DistUnlock(player.PlayerID)
|
||||
u.db.DistUnlock(player.PlayerID)
|
||||
}()
|
||||
playerCopy := new(model.Player)
|
||||
err := msgpack.Unmarshal(playerData, playerCopy)
|
||||
@@ -463,7 +463,7 @@ func (u *UserManager) saveUserHandle() {
|
||||
}
|
||||
|
||||
func (u *UserManager) LoadUserFromDbSync(userId uint32) *model.Player {
|
||||
player, err := u.dao.QueryPlayerByID(userId)
|
||||
player, err := u.db.QueryPlayerById(userId)
|
||||
if err != nil {
|
||||
logger.Error("query player error: %v", err)
|
||||
return nil
|
||||
@@ -473,13 +473,13 @@ func (u *UserManager) LoadUserFromDbSync(userId uint32) *model.Player {
|
||||
|
||||
func (u *UserManager) SaveUserToDbSync(player *model.Player) {
|
||||
if player.DbState == model.DbInsert {
|
||||
err := u.dao.InsertPlayer(player)
|
||||
err := u.db.InsertPlayer(player)
|
||||
if err != nil {
|
||||
logger.Error("insert player error: %v", err)
|
||||
return
|
||||
}
|
||||
} else if player.DbState == model.DbNormal || player.DbState == model.DbDelete {
|
||||
err := u.dao.UpdatePlayer(player)
|
||||
err := u.db.UpdatePlayer(player)
|
||||
if err != nil {
|
||||
logger.Error("update player error: %v", err)
|
||||
return
|
||||
@@ -490,12 +490,12 @@ func (u *UserManager) SaveUserToDbSync(player *model.Player) {
|
||||
}
|
||||
|
||||
func (u *UserManager) SaveUserListToDbSync(insertPlayerList []*model.Player, updatePlayerList []*model.Player) {
|
||||
err := u.dao.InsertPlayerList(insertPlayerList)
|
||||
err := u.db.InsertPlayerList(insertPlayerList)
|
||||
if err != nil {
|
||||
logger.Error("insert player list error: %v", err)
|
||||
return
|
||||
}
|
||||
err = u.dao.UpdatePlayerList(updatePlayerList)
|
||||
err = u.db.UpdatePlayerList(updatePlayerList)
|
||||
if err != nil {
|
||||
logger.Error("update player list error: %v", err)
|
||||
return
|
||||
@@ -505,7 +505,7 @@ func (u *UserManager) SaveUserListToDbSync(insertPlayerList []*model.Player, upd
|
||||
|
||||
func (u *UserManager) LoadUserChatMsgFromDbSync(userId uint32) map[uint32][]*model.ChatMsg {
|
||||
chatMsgMap := make(map[uint32][]*model.ChatMsg)
|
||||
chatMsgList, err := u.dao.QueryChatMsgListByUid(userId)
|
||||
chatMsgList, err := u.db.QueryChatMsgListByUid(userId)
|
||||
if err != nil {
|
||||
logger.Error("query chat msg list error: %v", err)
|
||||
return chatMsgMap
|
||||
@@ -539,7 +539,7 @@ func (u *UserManager) LoadUserChatMsgFromDbSync(userId uint32) map[uint32][]*mod
|
||||
}
|
||||
|
||||
func (u *UserManager) SaveUserChatMsgToDbSync(chatMsg *model.ChatMsg) {
|
||||
err := u.dao.InsertChatMsg(chatMsg)
|
||||
err := u.db.InsertChatMsg(chatMsg)
|
||||
if err != nil {
|
||||
logger.Error("insert chat msg error: %v", err)
|
||||
return
|
||||
@@ -547,7 +547,7 @@ func (u *UserManager) SaveUserChatMsgToDbSync(chatMsg *model.ChatMsg) {
|
||||
}
|
||||
|
||||
func (u *UserManager) ReadAndUpdateUserChatMsgToDbSync(uid uint32, targetUid uint32) {
|
||||
err := u.dao.ReadAndUpdateChatMsgByUid(uid, targetUid)
|
||||
err := u.db.ReadAndUpdateChatMsgByUid(uid, targetUid)
|
||||
if err != nil {
|
||||
logger.Error("read chat msg error: %v", err)
|
||||
return
|
||||
@@ -555,14 +555,14 @@ func (u *UserManager) ReadAndUpdateUserChatMsgToDbSync(uid uint32, targetUid uin
|
||||
}
|
||||
|
||||
func (u *UserManager) LoadUserFromRedisSync(userId uint32) *model.Player {
|
||||
player := u.dao.GetRedisPlayer(userId)
|
||||
player := u.db.GetRedisPlayer(userId)
|
||||
return player
|
||||
}
|
||||
|
||||
func (u *UserManager) SaveUserToRedisSync(player *model.Player) {
|
||||
u.dao.SetRedisPlayer(player)
|
||||
u.db.SetRedisPlayer(player)
|
||||
}
|
||||
|
||||
func (u *UserManager) SaveUserListToRedisSync(setPlayerList []*model.Player) {
|
||||
u.dao.SetRedisPlayerList(setPlayerList)
|
||||
u.db.SetRedisPlayerList(setPlayerList)
|
||||
}
|
||||
@@ -12,11 +12,11 @@ const (
|
||||
type ChatMsg struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty"`
|
||||
Sequence uint32 `bson:"-"`
|
||||
Time uint32 `bson:"Time"`
|
||||
Uid uint32 `bson:"Uid"`
|
||||
ToUid uint32 `bson:"ToUid"`
|
||||
IsRead bool `bson:"IsRead"`
|
||||
MsgType uint8 `bson:"MsgType"`
|
||||
Text string `bson:"Text"`
|
||||
Icon uint32 `bson:"Icon"`
|
||||
Time uint32 `bson:"time"`
|
||||
Uid uint32 `bson:"uid"`
|
||||
ToUid uint32 `bson:"to_uid"`
|
||||
IsRead bool `bson:"is_read"`
|
||||
MsgType uint8 `bson:"msg_type"`
|
||||
Text string `bson:"text"`
|
||||
Icon uint32 `bson:"icon"`
|
||||
}
|
||||
+1
-1
@@ -26,7 +26,7 @@ type GameObject interface {
|
||||
type Player struct {
|
||||
// 离线数据 请尽量不要定义接口等复杂数据结构
|
||||
ID primitive.ObjectID `bson:"_id,omitempty"`
|
||||
PlayerID uint32 `bson:"PlayerID"` // 玩家uid
|
||||
PlayerID uint32 `bson:"player_id"` // 玩家uid
|
||||
IsBorn bool // 是否完成开场动画
|
||||
NickName string // 昵称
|
||||
Signature string // 签名
|
||||
|
||||
@@ -32,6 +32,8 @@ service Discovery {
|
||||
rpc GetWhiteList (NullMsg) returns (GetWhiteListRsp) {}
|
||||
// 修改停服维护白名单
|
||||
rpc SetWhiteList (SetWhiteListReq) returns (NullMsg) {}
|
||||
// 获取下一个自增uid
|
||||
rpc GetNextUid (NullMsg) returns (GetNextUidRsp) {}
|
||||
}
|
||||
|
||||
message NullMsg {
|
||||
@@ -118,3 +120,7 @@ message SetWhiteListReq {
|
||||
bool is_add = 1;
|
||||
string ip_addr = 2;
|
||||
}
|
||||
|
||||
message GetNextUidRsp {
|
||||
uint32 uid = 1;
|
||||
}
|
||||
+8
-1
@@ -10,6 +10,7 @@ import (
|
||||
"hk4e/common/config"
|
||||
"hk4e/common/mq"
|
||||
"hk4e/node/api"
|
||||
"hk4e/node/dao"
|
||||
"hk4e/node/service"
|
||||
"hk4e/pkg/logger"
|
||||
|
||||
@@ -37,7 +38,13 @@ func Run(ctx context.Context, configFile string) error {
|
||||
messageQueue := mq.NewMessageQueue(api.NODE, "node", nil)
|
||||
defer messageQueue.Close()
|
||||
|
||||
s, err := service.NewService(conn, messageQueue)
|
||||
db, err := dao.NewDao()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.CloseDao()
|
||||
|
||||
s, err := service.NewService(db, conn, messageQueue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hk4e/common/config"
|
||||
"hk4e/pkg/logger"
|
||||
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||
)
|
||||
|
||||
type Dao struct {
|
||||
mongo *mongo.Client
|
||||
db *mongo.Database
|
||||
}
|
||||
|
||||
func NewDao() (*Dao, error) {
|
||||
r := new(Dao)
|
||||
|
||||
clientOptions := options.Client().ApplyURI(config.GetConfig().Database.Url).SetMinPoolSize(10).SetMaxPoolSize(100)
|
||||
client, err := mongo.Connect(context.TODO(), clientOptions)
|
||||
if err != nil {
|
||||
logger.Error("mongo connect error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
err = client.Ping(context.TODO(), readpref.Primary())
|
||||
if err != nil {
|
||||
logger.Error("mongo ping error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
r.mongo = client
|
||||
r.db = client.Database("node_hk4e")
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (d *Dao) CloseDao() {
|
||||
err := d.mongo.Disconnect(context.TODO())
|
||||
if err != nil {
|
||||
logger.Error("mongo close error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package dao
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
type Region struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty"`
|
||||
RegionId uint32 `bson:"region_id"`
|
||||
Ec2bData []byte `bson:"ec2b_data"`
|
||||
NextUid uint32 `bson:"next_uid"`
|
||||
}
|
||||
|
||||
func (d *Dao) InsertRegion(region *Region) error {
|
||||
db := d.db.Collection("region")
|
||||
region.RegionId = 1
|
||||
_, err := db.InsertOne(context.TODO(), region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) DeleteRegion() error {
|
||||
db := d.db.Collection("region")
|
||||
_, err := db.DeleteOne(context.TODO(), bson.D{{"region_id", 1}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) UpdateRegion(region *Region) error {
|
||||
db := d.db.Collection("region")
|
||||
region.RegionId = 1
|
||||
_, err := db.UpdateMany(
|
||||
context.TODO(),
|
||||
bson.D{{"region_id", 1}},
|
||||
bson.D{{"$set", region}},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dao) QueryRegion() (*Region, error) {
|
||||
db := d.db.Collection("region")
|
||||
result := db.FindOne(
|
||||
context.TODO(),
|
||||
bson.D{{"region_id", 1}},
|
||||
)
|
||||
region := new(Region)
|
||||
err := result.Decode(region)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return region, nil
|
||||
}
|
||||
@@ -7,17 +7,19 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"hk4e/common/mq"
|
||||
"hk4e/common/region"
|
||||
"hk4e/node/api"
|
||||
"hk4e/node/dao"
|
||||
"hk4e/pkg/logger"
|
||||
"hk4e/pkg/random"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxGsId = 1000
|
||||
MaxGsId = 1000
|
||||
UidBegin = 100000000
|
||||
)
|
||||
|
||||
var _ api.DiscoveryNATSRPCServer = (*DiscoveryService)(nil)
|
||||
@@ -45,7 +47,9 @@ type StopServerInfo struct {
|
||||
}
|
||||
|
||||
type DiscoveryService struct {
|
||||
db *dao.Dao // 数据库访问对象
|
||||
regionEc2b *random.Ec2b // 区服密钥信息
|
||||
nextUid uint32 // 自增uid
|
||||
serverInstanceMap map[string]*sync.Map // 全部服务器实例集合 key:服务器类型 value:服务器实例集合 -> key:appid value:服务器实例
|
||||
serverAppIdMap *sync.Map // 服务器appid集合 key:appid value:是否存在
|
||||
globalGsOnlineMap *sync.Map // 全服玩家在线集合 key:uid value:gsAppid
|
||||
@@ -53,10 +57,33 @@ type DiscoveryService struct {
|
||||
messageQueue *mq.MessageQueue // 消息队列实例
|
||||
}
|
||||
|
||||
func NewDiscoveryService(messageQueue *mq.MessageQueue) *DiscoveryService {
|
||||
func NewDiscoveryService(db *dao.Dao, messageQueue *mq.MessageQueue) (*DiscoveryService, error) {
|
||||
r := new(DiscoveryService)
|
||||
r.regionEc2b = region.LoadRegionEc2b()
|
||||
logger.Info("region ec2b create ok, seed: %v", r.regionEc2b.Seed())
|
||||
r.db = db
|
||||
region, err := r.db.QueryRegion()
|
||||
if err != nil {
|
||||
logger.Error("load region from db error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if region == nil {
|
||||
logger.Info("init region")
|
||||
region = &dao.Region{
|
||||
Ec2bData: random.NewEc2b().Bytes(),
|
||||
NextUid: UidBegin,
|
||||
}
|
||||
err := r.db.InsertRegion(region)
|
||||
if err != nil {
|
||||
logger.Error("save region to db error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
r.regionEc2b, err = random.LoadEc2bKey(region.Ec2bData)
|
||||
if err != nil {
|
||||
logger.Error("parse ec2b data error: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
logger.Info("region ec2b load ok, seed: %v", r.regionEc2b.Seed())
|
||||
r.nextUid = region.NextUid
|
||||
r.serverInstanceMap = make(map[string]*sync.Map)
|
||||
r.serverInstanceMap[api.GATE] = new(sync.Map)
|
||||
r.serverInstanceMap[api.GS] = new(sync.Map)
|
||||
@@ -75,7 +102,19 @@ func NewDiscoveryService(messageQueue *mq.MessageQueue) *DiscoveryService {
|
||||
r.messageQueue = messageQueue
|
||||
go r.removeDeadServer()
|
||||
go r.broadcastReceiver()
|
||||
return r
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *DiscoveryService) close() {
|
||||
region := &dao.Region{
|
||||
Ec2bData: s.regionEc2b.Bytes(),
|
||||
NextUid: s.nextUid,
|
||||
}
|
||||
err := s.db.UpdateRegion(region)
|
||||
if err != nil {
|
||||
logger.Error("save region to db error: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DiscoveryService) broadcastReceiver() {
|
||||
@@ -370,6 +409,13 @@ func (s *DiscoveryService) SetWhiteList(ctx context.Context, req *api.SetWhiteLi
|
||||
return &api.NullMsg{}, nil
|
||||
}
|
||||
|
||||
// GetNextUid 获取下一个自增uid
|
||||
func (s *DiscoveryService) GetNextUid(ctx context.Context, req *api.NullMsg) (*api.GetNextUidRsp, error) {
|
||||
return &api.GetNextUidRsp{
|
||||
Uid: atomic.AddUint32(&s.nextUid, 1),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *DiscoveryService) getRandomServerInstance(instMap *sync.Map) *ServerInstance {
|
||||
instList := make([]*ServerInstance, 0)
|
||||
instMap.Range(func(key, value any) bool {
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"hk4e/common/mq"
|
||||
"hk4e/node/api"
|
||||
"hk4e/node/dao"
|
||||
|
||||
"github.com/byebyebruce/natsrpc"
|
||||
"github.com/nats-io/nats.go"
|
||||
@@ -10,10 +11,11 @@ import (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db *dao.Dao
|
||||
discoveryService *DiscoveryService
|
||||
}
|
||||
|
||||
func NewService(conn *nats.Conn, messageQueue *mq.MessageQueue) (*Service, error) {
|
||||
func NewService(db *dao.Dao, conn *nats.Conn, messageQueue *mq.MessageQueue) (*Service, error) {
|
||||
enc, err := nats.NewEncodedConn(conn, protobuf.PROTOBUF_ENCODER)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -22,16 +24,21 @@ func NewService(conn *nats.Conn, messageQueue *mq.MessageQueue) (*Service, error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
discoveryService := NewDiscoveryService(messageQueue)
|
||||
discoveryService, err := NewDiscoveryService(db, messageQueue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = api.RegisterDiscoveryNATSRPCServer(svr, discoveryService)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &Service{
|
||||
db: db,
|
||||
discoveryService: discoveryService,
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Service) Close() {
|
||||
s.discoveryService.close()
|
||||
}
|
||||
Reference in new issue
Block a user