首次登陆创建用户数据

This commit is contained in:
liuxiaobo 2025-06-06 00:09:10 +08:00
parent 91afff4451
commit bcf13ae137
26 changed files with 268 additions and 110 deletions

View File

@ -1,16 +1,17 @@
package config package config
import ( import (
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
"testing" "testing"
) )
const ( const (
redisHost = "114.132.124.145" redisHost = "114.132.124.145"
redisPort = "6379" //redisPort = "6379"
redisPassword = "fox379@@zyxi" //redisPassword = "fox379@@zyxi"
specialKey = "test_config" specialKey = "test_config"
) )
func initLog() { func initLog() {
@ -23,12 +24,12 @@ type specialConfig struct {
func TestConfig(t *testing.T) { func TestConfig(t *testing.T) {
initLog() initLog()
rdb, err := db.InitRedis(redisPassword, redisHost, redisPort, 0) rdb, err := db.InitRedis(redisPassword, redisHost, redisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return
} }
comm, err := LoadCommonConfig[specialConfig](rdb) comm, err := LoadCommonConfig[specialConfig](rdb, "", "", "")
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

11
common/constant/redis.go Normal file
View File

@ -0,0 +1,11 @@
package constant
/*
*/
const (
Redis0Config = 0 // redis中0号给配置信息
Redis1User = 1 // redis中1号给玩家数据及玩家资源数据
Redis2Account = 2 // redis中2号给玩家帐号数据
Redis3UserBindService = 3 // redis中3号给玩家绑定的服务
Redis4Log = 4 // redis中4号给各类需要处理的日志
)

View File

@ -22,7 +22,7 @@ type resultT[T any] struct {
} }
type iTable interface { type iTable interface {
GetId() uint GetId() int64
TableName() string TableName() string
} }
@ -43,11 +43,11 @@ func (s *TableOp[T]) tableName() string {
return result.ret.TableName() return result.ret.TableName()
} }
func (s *TableOp[T]) redisKey(id uint) string { func (s *TableOp[T]) redisKey(id int64) string {
return fmt.Sprintf("%s:%d", s.tableName(), id) return fmt.Sprintf("%s:%d", s.tableName(), id)
} }
func (s *TableOp[T]) findByRedis(id uint) *T { func (s *TableOp[T]) findByRedis(id int64) *T {
if s.rds == nil { if s.rds == nil {
return nil return nil
} }
@ -68,7 +68,7 @@ func (s *TableOp[T]) findByRedis(id uint) *T {
return us return us
} }
func (s *TableOp[T]) writeRedis(id uint, t *T) { func (s *TableOp[T]) writeRedis(id int64, t *T) {
if s.rds == nil { if s.rds == nil {
return return
} }
@ -79,7 +79,7 @@ func (s *TableOp[T]) writeRedis(id uint, t *T) {
s.updateRedis(id, maps) s.updateRedis(id, maps)
} }
func (s *TableOp[T]) updateRedis(id uint, maps map[string]any) { func (s *TableOp[T]) updateRedis(id int64, maps map[string]any) {
if s.rds == nil { if s.rds == nil {
return return
} }
@ -89,7 +89,7 @@ func (s *TableOp[T]) updateRedis(id uint, maps map[string]any) {
_ = s.rds.Expire(context.Background(), s.redisKey(id), TableExpire).Err() _ = s.rds.Expire(context.Background(), s.redisKey(id), TableExpire).Err()
} }
func (s *TableOp[T]) deleteRedis(id uint) { func (s *TableOp[T]) deleteRedis(id int64) {
if s.rds == nil { if s.rds == nil {
return return
} }
@ -105,7 +105,7 @@ func (s *TableOp[T]) Create(t *T) (*T, pb.ErrCode) {
return t, pb.ErrCode_OK return t, pb.ErrCode_OK
} }
func (s *TableOp[T]) Find(id uint) (*T, pb.ErrCode) { func (s *TableOp[T]) Find(id int64) (*T, pb.ErrCode) {
// 先从redis中查询redis中没有则从mysql中查询 // 先从redis中查询redis中没有则从mysql中查询
if table := s.findByRedis(id); table != nil { if table := s.findByRedis(id); table != nil {
return table, pb.ErrCode_OK return table, pb.ErrCode_OK
@ -135,7 +135,7 @@ func (s *TableOp[T]) FindCondition(condition map[string]any) (*T, error) {
return &result.ret, nil return &result.ret, nil
} }
func (s *TableOp[T]) Update(id uint, updates map[string]any) (*T, pb.ErrCode) { func (s *TableOp[T]) Update(id int64, updates map[string]any) (*T, pb.ErrCode) {
var result resultT[T] var result resultT[T]
err := s.db.Model(&result.ret).Where("id = ?", id).Updates(updates).Error err := s.db.Model(&result.ret).Where("id = ?", id).Updates(updates).Error
if err != nil { if err != nil {
@ -146,7 +146,7 @@ func (s *TableOp[T]) Update(id uint, updates map[string]any) (*T, pb.ErrCode) {
return &result.ret, pb.ErrCode_OK return &result.ret, pb.ErrCode_OK
} }
func (s *TableOp[T]) Delete(id uint) (*T, pb.ErrCode) { func (s *TableOp[T]) Delete(id int64) (*T, pb.ErrCode) {
var result resultT[T] var result resultT[T]
err := s.db.Delete(&result.ret, id).Error err := s.db.Delete(&result.ret, id).Error
if err != nil { if err != nil {

View File

@ -2,15 +2,15 @@ package user
// 玩家账户表 // 玩家账户表
type User struct { type User struct {
ID uint `gorm:"primarykey;autoIncrement" json:"id"` ID int64 `gorm:"primarykey;autoIncrement" json:"id"`
accountId uint `gorm:"type:bigint;uniqueIndex;not null"` // 帐号id AccountId int64 `gorm:"uniqueIndex;not null" json:"account_id"` // 帐号id
Nickname string `gorm:"type:varchar(32);uniqueIndex;not null"` // 昵称 Nickname string `gorm:"type:varchar(32);uniqueIndex;not null" json:"nickname"` // 昵称
AvatarUrl string `gorm:"type:varchar(255)"` // 头像 AvatarUrl string `gorm:"type:varchar(255)" json:"avatar_url"` // 头像
AvatarFrame string `gorm:"type:varchar(255)"` // 头像框 AvatarFrame string `gorm:"type:varchar(255)" json:"avatar_frame"` // 头像框
VipExp int32 `gorm:"type:int"` // vip经验值 VipExp int32 `gorm:"type:int" json:"vip_exp"` // vip经验值
} }
func (u User) GetId() uint { func (u User) GetId() int64 {
return u.ID return u.ID
} }

View File

@ -12,7 +12,7 @@ const (
// 玩家账户表 // 玩家账户表
type UserAccount struct { type UserAccount struct {
ID uint `gorm:"primarykey;autoIncrement" json:"id"` ID int64 `gorm:"primarykey;autoIncrement" json:"id"`
Username string `gorm:"type:varchar(32);uniqueIndex;not null" json:"username"` // 用户名 Username string `gorm:"type:varchar(32);uniqueIndex;not null" json:"username"` // 用户名
Password string `gorm:"type:varchar(255);not null" json:"password"` // 密码哈希 Password string `gorm:"type:varchar(255);not null" json:"password"` // 密码哈希
Email string `gorm:"type:varchar(100)" json:"email"` // 邮箱(可选) Email string `gorm:"type:varchar(100)" json:"email"` // 邮箱(可选)
@ -25,7 +25,7 @@ type UserAccount struct {
RegisterTime time.Time `gorm:"type:TIMESTAMP;default:CURRENT_TIMESTAMP" json:"register_time"` // 注册时间 RegisterTime time.Time `gorm:"type:TIMESTAMP;default:CURRENT_TIMESTAMP" json:"register_time"` // 注册时间
} }
func (u UserAccount) GetId() uint { func (u UserAccount) GetId() int64 {
return u.ID return u.ID
} }
@ -35,8 +35,8 @@ func (u UserAccount) TableName() string {
// 玩家登录记录表 // 玩家登录记录表
type UserLoginLog struct { type UserLoginLog struct {
ID uint `gorm:"primarykey;autoIncrement" json:"id"` ID int64 `gorm:"primarykey;autoIncrement" json:"id"`
UID uint `gorm:"index" json:"uid"` // 关联玩家ID AccountID int64 `gorm:"index" json:"account_id"` // 关联帐号ID
LoginIP string `gorm:"type:varchar(45);not null" json:"login_ip"` // 登录IP LoginIP string `gorm:"type:varchar(45);not null" json:"login_ip"` // 登录IP
LoginTime time.Time `gorm:"type:TIMESTAMP;default:CURRENT_TIMESTAMP" json:"login_time"` // 登录时间 LoginTime time.Time `gorm:"type:TIMESTAMP;default:CURRENT_TIMESTAMP" json:"login_time"` // 登录时间
DeviceInfo string `gorm:"type:varchar(255)" json:"device_info"` // 设备信息(JSON格式) DeviceInfo string `gorm:"type:varchar(255)" json:"device_info"` // 设备信息(JSON格式)
@ -44,7 +44,7 @@ type UserLoginLog struct {
FailReason string `gorm:"type:varchar(100)" json:"fail_reason"` // 失败原因 FailReason string `gorm:"type:varchar(100)" json:"fail_reason"` // 失败原因
} }
func (u UserLoginLog) GetId() uint { func (u UserLoginLog) GetId() int64 {
return u.ID return u.ID
} }

View File

@ -2,16 +2,13 @@ package user
// 玩家账户表 // 玩家账户表
type UserResources struct { type UserResources struct {
ID uint `gorm:"primarykey;autoIncrement" json:"id"` UID int64 `gorm:"uniqueIndex" json:"id"`
accountId uint `gorm:"type:bigint;uniqueIndex;not null"` // 帐号id Gold int64 `gorm:"default:0" json:"gold"` // 金币
Nickname string `gorm:"type:varchar(32);uniqueIndex;not null"` // 昵称 Diamond int64 `gorm:"default:0" json:"diamond"` // 钻石
AvatarUrl string `gorm:"type:varchar(255)"` // 头像
AvatarFrame string `gorm:"type:varchar(255)"` // 头像框
VipExp int32 `gorm:"type:int"` // vip经验值
} }
func (u UserResources) GetId() uint { func (u UserResources) GetId() int64 {
return u.ID return u.UID
} }
func (u UserResources) TableName() string { func (u UserResources) TableName() string {

View File

@ -1,8 +1,12 @@
package rpcName package rpcName
const ( const (
// 用户、用户资源及帐号相关操作
GetUserAccount = "get.user.account.rpc" GetUserAccount = "get.user.account.rpc"
CreateUserAccount = "create.user.account.rpc" CreateUserAccount = "create.user.account.rpc"
UpdateUserPassword = "update.user.password.rpc" UpdateUserPassword = "update.user.password.rpc"
LogUserAccountLogin = "user.login.rpc" LogUserAccountLogin = "user.login.rpc"
GetUserByUid = "get.user.uid.rpc"
GetUserByAccountId = "get.user.account.id.rpc"
GetUserResources = "get.user.resources.rpc"
) )

View File

@ -2,6 +2,7 @@ package config
import ( import (
"game/common/config" "game/common/config"
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
) )
@ -22,7 +23,7 @@ func InitLog() {
func LoadConfig(GitCommit, GitBranch, BuildDate string) { func LoadConfig(GitCommit, GitBranch, BuildDate string) {
Command = config.ParseCommand() Command = config.ParseCommand()
rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, 0) rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

View File

@ -1,6 +1,7 @@
package model package model
import ( import (
"game/common/constant"
"game/server/chat/config" "game/server/chat/config"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
@ -11,7 +12,7 @@ var UserRedis *redis.Client
var err error var err error
func InitRedis() { func InitRedis() {
UserRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, 0) UserRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, constant.Redis1User)
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
return return

View File

@ -2,6 +2,7 @@ package config
import ( import (
"game/common/config" "game/common/config"
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
) )
@ -25,7 +26,7 @@ func initLog() {
func LoadConfig(GitCommit, GitBranch, BuildDate string) { func LoadConfig(GitCommit, GitBranch, BuildDate string) {
Command = config.ParseCommand() Command = config.ParseCommand()
initLog() initLog()
rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, 0) rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

View File

@ -1,19 +1,12 @@
package model package model
import ( //var UserRedis *redis.Client
"game/server/client/config" //var err error
"github.com/fox/fox/db" //
"github.com/fox/fox/log" //func InitRedis() {
"github.com/go-redis/redis/v8" // UserRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, 0)
) // if err != nil {
// log.Fatal(err.Error())
var UserRedis *redis.Client // return
var err error // }
//}
func InitRedis() {
UserRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, 0)
if err != nil {
log.Fatal(err.Error())
return
}
}

View File

@ -2,6 +2,7 @@ package config
import ( import (
"game/common/config" "game/common/config"
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
) )
@ -22,7 +23,7 @@ func InitLog() {
func LoadConfig(GitCommit, GitBranch, BuildDate string) { func LoadConfig(GitCommit, GitBranch, BuildDate string) {
Command = config.ParseCommand() Command = config.ParseCommand()
rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, 0) rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

View File

@ -1,6 +1,7 @@
package operation package operation
import ( import (
"game/common/constant"
"game/common/model/user" "game/common/model/user"
"game/common/utils" "game/common/utils"
"game/server/db/config" "game/server/db/config"
@ -21,13 +22,13 @@ func InitRedis() {
log.Debug("init redis") log.Debug("init redis")
var err error var err error
cfg := &config.Cfg.Redis cfg := &config.Cfg.Redis
UserRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, 0) UserRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, constant.Redis1User)
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
return return
} }
utils.AutoSetRedisPool(UserRedis) utils.AutoSetRedisPool(UserRedis)
AccountRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, 1) AccountRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, constant.Redis2Account)
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
return return

View File

@ -1,16 +1 @@
package operation package operation
import (
"game/common/model"
"game/common/model/user"
)
// 玩家表
func NewUserOp() *model.TableOp[user.User] {
return model.NewTableOp[user.User](UserDB, UserRedis)
}
// 玩家资源表
func NewUserResourcesOp() *model.TableOp[user.UserResources] {
return model.NewTableOp[user.UserResources](UserDB, UserRedis)
}

112
server/db/operation/user.go Normal file
View File

@ -0,0 +1,112 @@
package operation
import (
"context"
"errors"
"fmt"
"game/common/model"
"game/common/model/user"
"game/common/proto/pb"
"game/common/serialization"
"game/common/utils"
"github.com/fox/fox/log"
"github.com/fox/fox/xrand"
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
"gorm.io/gorm"
"strconv"
)
type UserOp struct {
db *gorm.DB
userRedis *redis.Client
*model.TableOp[user.User]
}
// 玩家表
func NewUserOp() *UserOp {
return &UserOp{
db: UserDB,
userRedis: UserRedis,
TableOp: model.NewTableOp[user.User](UserDB, UserRedis),
}
}
func (s *UserOp) redisKey(accountId int64) string {
return fmt.Sprintf("account_id:%v", accountId)
}
func (s *UserOp) GetUserByAccountId(accountId int64) (*user.User, pb.ErrCode) {
sUid, err := s.userRedis.Get(context.Background(), s.redisKey(accountId)).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
us := &user.User{}
err = s.db.Where("account_id = ?", accountId).First(us).Error
if err != nil {
log.DebugF("find user by account id:%v err:%v", accountId, err)
return nil, pb.ErrCode_SystemErr
}
// 从db中查到后写入redis并建立索引
if us.ID > 0 {
_, _ = s.Update(us.ID, serialization.StructToMap(us))
_ = s.userRedis.Set(context.Background(), s.redisKey(accountId), us.ID, model.TableExpire).Err()
} else {
// db中没有则创建玩家
return s.createUserAccountId(accountId)
}
return us, pb.ErrCode_OK
} else {
log.ErrorF("find user by account id:%v err:%v", accountId, err)
return nil, pb.ErrCode_SystemErr
}
}
uid, _ := strconv.ParseInt(sUid, 10, 64)
if uid < 0 {
log.ErrorF("get user failed, account id:%d, uid:%v", accountId, sUid)
return nil, pb.ErrCode_SystemErr
}
return s.Find(uid)
}
func (s *UserOp) generateUniqueNickname(db *gorm.DB) (string, error) {
// 基础昵称模板
baseNick := "用户_" + uuid.New().String()[:8]
nickname := baseNick
// 检查是否唯一,不唯一则追加随机字符
for i := 0; i < 5; i++ { // 最多尝试5次
var count int64
err := db.Model(&user.User{}).Where("nickname = ?", nickname).Count(&count).Error
if err != nil {
return "", err
}
if count == 0 {
return nickname, nil
}
nickname = baseNick + xrand.RandomString(2) // 追加2位随机字符
}
return "", fmt.Errorf("无法生成唯一昵称")
}
// 创建用户
func (s *UserOp) createUserAccountId(accountId int64) (*user.User, pb.ErrCode) {
nickname, err := s.generateUniqueNickname(s.db)
if err != nil {
log.ErrorF("generate unique nickname err:%v", err)
return nil, pb.ErrCode_SystemErr
}
us := &user.User{
AccountId: accountId,
Nickname: nickname,
}
var code pb.ErrCode
us, code = s.Create(us)
log.DebugF("create user:%v", utils.JsonMarshal(us))
if code != pb.ErrCode_OK {
return nil, code
}
// 建立索引
_ = s.userRedis.Set(context.Background(), s.redisKey(us.AccountId), us.ID, model.TableExpire).Err()
return us, pb.ErrCode_OK
}

View File

@ -61,7 +61,7 @@ func (s *UserAccountOp) GetUserAccount(username string) (*user.UserAccount, pb.E
log.ErrorF("get user account:%v failed, uid is: %d", username, uid) log.ErrorF("get user account:%v failed, uid is: %d", username, uid)
return nil, pb.ErrCode_SystemErr return nil, pb.ErrCode_SystemErr
} }
return s.accountOp.Find(uint(uid)) return s.accountOp.Find(uid)
} }
// 创建用户 // 创建用户

View File

@ -0,0 +1,11 @@
package operation
import (
"game/common/model"
"game/common/model/user"
)
// 玩家资源表
func NewUserResourcesOp() *model.TableOp[user.UserResources] {
return model.NewTableOp[user.UserResources](UserDB, UserRedis)
}

View File

@ -63,22 +63,30 @@ func (s *DbService) onLogUserAccountLogin(iMsg *ipb.InternalMsg) *ipb.InternalMs
return iMsg return iMsg
} }
//func (s *DbService) operation(iMsg *ipb.InternalMsg, operation func(us *user.UserAccount) (*user.UserAccount, pb.ErrCode)) { // 获取用户数据,没有则创建
// us := &user.UserAccount{} func (s *DbService) onGetUserByAccountId(iMsg *ipb.InternalMsg) *ipb.InternalMsg {
// err := json.Unmarshal(iMsg.Msg, us) operationDb[user.User](iMsg, func(us *user.User) (*user.User, pb.ErrCode) {
// if err != nil { return operation.NewUserOp().GetUserByAccountId(us.AccountId)
// log.ErrorF("error unmarshalling user account %v", err) })
// return return iMsg
// } }
// var code pb.ErrCode
// us, code = operation(us) // 获取用户数据,没有则创建
// if code != pb.ErrCode_OK { func (s *DbService) onGetUserByUid(iMsg *ipb.InternalMsg) *ipb.InternalMsg {
// return operationDb[user.User](iMsg, func(us *user.User) (*user.User, pb.ErrCode) {
// } return operation.NewUserOp().Find(us.ID)
// iMsg.Msg, err = json.Marshal(us) })
// if err != nil { return iMsg
// log.ErrorF("error marshalling user account %v", err) }
// return
// } // 获取用户数据,没有则创建
// return func (s *DbService) onGetUserResources(iMsg *ipb.InternalMsg) *ipb.InternalMsg {
//} operationDb[user.UserResources](iMsg, func(res *user.UserResources) (*user.UserResources, pb.ErrCode) {
if us1, code := operation.NewUserResourcesOp().Find(res.UID); code != pb.ErrCode_OK {
return operation.NewUserResourcesOp().Create(res)
} else {
return us1, code
}
})
return iMsg
}

View File

@ -11,5 +11,8 @@ func (s *DbService) initRpcProcessor() {
rpcName.GetUserAccount: s.onGetUserAccount, rpcName.GetUserAccount: s.onGetUserAccount,
rpcName.UpdateUserPassword: s.onUpdateUserAccount, rpcName.UpdateUserPassword: s.onUpdateUserAccount,
rpcName.LogUserAccountLogin: s.onLogUserAccountLogin, rpcName.LogUserAccountLogin: s.onLogUserAccountLogin,
rpcName.GetUserByUid: s.onGetUserByUid,
rpcName.GetUserByAccountId: s.onGetUserByAccountId,
rpcName.GetUserResources: s.onGetUserResources,
}) })
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"game/common/config" "game/common/config"
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
) )
@ -31,7 +32,7 @@ func InitLog() {
func LoadConfig(GitCommit, GitBranch, BuildDate string) { func LoadConfig(GitCommit, GitBranch, BuildDate string) {
Command = config.ParseCommand() Command = config.ParseCommand()
rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, 0) rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

View File

@ -1,6 +1,7 @@
package model package model
import ( import (
"game/common/constant"
"game/common/utils" "game/common/utils"
"game/server/gate/config" "game/server/gate/config"
"github.com/fox/fox/db" "github.com/fox/fox/db"
@ -8,14 +9,14 @@ import (
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
) )
var UserRedis *redis.Client var UserBindServiceRedis *redis.Client
var err error var err error
func InitRedis() { func InitRedis() {
UserRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, 0) UserBindServiceRedis, err = db.InitRedis(config.Cfg.Redis.Password, config.Cfg.Redis.Host, config.Cfg.Redis.Port, constant.Redis3UserBindService)
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
return return
} }
utils.AutoSetRedisPool(UserRedis) utils.AutoSetRedisPool(UserBindServiceRedis)
} }

View File

@ -71,7 +71,7 @@ func newGateService(serviceId int) *GateService {
} }
wsAddress := config.Cfg.Special.Address[addressPos] wsAddress := config.Cfg.Special.Address[addressPos]
s.wss = ws.NewWsServer(wsAddress, s.WsOnMessage, s.WsOnDisconnect) s.wss = ws.NewWsServer(wsAddress, s.WsOnMessage, s.WsOnDisconnect)
s.bindService = userBindService.NewUserBindService(model.UserRedis, s.ServiceEtcd()) s.bindService = userBindService.NewUserBindService(model.UserBindServiceRedis, s.ServiceEtcd())
s.processor = processor.NewProcessor() s.processor = processor.NewProcessor()
s.initProcessor() s.initProcessor()

View File

@ -2,6 +2,7 @@ package config
import ( import (
"game/common/config" "game/common/config"
"game/common/constant"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
) )
@ -22,7 +23,7 @@ func InitLog() {
func LoadConfig(GitCommit, GitBranch, BuildDate string) { func LoadConfig(GitCommit, GitBranch, BuildDate string) {
Command = config.ParseCommand() Command = config.ParseCommand()
rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, 0) rdb, err := db.InitRedis(Command.RedisPassword, Command.RedisHost, Command.RedisPort, constant.Redis0Config)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return

View File

@ -1,6 +1,7 @@
package model package model
import ( import (
"game/common/constant"
"game/server/login/config" "game/server/login/config"
"github.com/fox/fox/db" "github.com/fox/fox/db"
"github.com/fox/fox/log" "github.com/fox/fox/log"
@ -8,7 +9,7 @@ import (
) )
var ( var (
UserRedis *redis.Client UserBindServiceRedis *redis.Client
//UserDB *gorm.DB //UserDB *gorm.DB
//LogDB *gorm.DB //LogDB *gorm.DB
) )
@ -17,7 +18,7 @@ func InitRedis() {
log.Debug("init redis") log.Debug("init redis")
var err error var err error
cfg := &config.Cfg.Redis cfg := &config.Cfg.Redis
UserRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, 0) UserBindServiceRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, constant.Redis3UserBindService)
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
return return

View File

@ -88,7 +88,7 @@ func (s *LoginService) checkLoginOrRegister(req *pb.C2SUserLogin) (us *user.User
} }
// 生成JWT令牌(简化版) // 生成JWT令牌(简化版)
func generateToken(userID uint, username string) (string, error) { func generateToken(userID int64, username string) (string, error) {
_ = userID _ = userID
_ = username _ = username
// 这里应该使用JWT库生成实际令牌 // 这里应该使用JWT库生成实际令牌
@ -96,22 +96,46 @@ func generateToken(userID uint, username string) (string, error) {
return "generated-token-placeholder", nil return "generated-token-placeholder", nil
} }
// 获取用户数据,如果没有则创建
func (s *LoginService) getUser(accountId int64, tName string) (*user.User, pb.ErrCode) {
us := &user.User{
AccountId: accountId,
}
rpcMsg := ipb.MakeRpcMsg[user.User](rpcName.GetUserByAccountId, 0, us)
rsp, err := s.Call(service.RpcTopicEx(tName), timeout, rpcMsg)
if err != nil {
log.ErrorF(s.Log("call rpc:%v err:%s", rpcMsg.RpcMsgId, err.Error()))
return nil, pb.ErrCode_SystemErr
}
_ = json.Unmarshal(rsp.Msg, us)
if us.ID == 0 {
log.ErrorF(s.Log("call rpc:%v return:%v", rpcMsg.RpcMsgId, string(rsp.Msg)))
return us, pb.ErrCode_SystemErr
}
return us, pb.ErrCode_OK
}
// 登录或注册 // 登录或注册
func (s *LoginService) onLoginOrRegister(iMsg *ipb.InternalMsg, req *pb.C2SUserLogin) { func (s *LoginService) onLoginOrRegister(iMsg *ipb.InternalMsg, req *pb.C2SUserLogin) {
ksync.GoSafe(func() { ksync.GoSafe(func() {
us, code, node := s.checkLoginOrRegister(req) account, code, node := s.checkLoginOrRegister(req)
userId := int64(0) userId := int64(0)
rsp := &pb.S2CUserLogin{Code: code} rsp := &pb.S2CUserLogin{Code: code}
if us != nil && code == pb.ErrCode_OK { if account != nil && code == pb.ErrCode_OK {
rsp.UserId = int64(us.ID) // 拉取用户数据
rsp.Token, _ = generateToken(us.ID, us.Username) us := &user.User{}
userId = rsp.UserId us, code = s.getUser(userId, req.Username)
if code == pb.ErrCode_OK {
rsp.UserId = us.ID
rsp.Token, _ = generateToken(account.ID, account.Username)
userId = rsp.UserId
}
} }
s.SendServiceMsg(service.TopicEx(iMsg.ServiceName), iMsg.ConnId, userId, int32(pb.MsgId_S2CUserLoginId), rsp) s.SendServiceMsg(service.TopicEx(iMsg.ServiceName), iMsg.ConnId, userId, int32(pb.MsgId_S2CUserLoginId), rsp)
if us != nil && us.ID > 0 { if account != nil && account.ID > 0 {
loginLog := &user.UserLoginLog{ loginLog := &user.UserLoginLog{
UID: us.ID, AccountID: account.ID,
LoginIP: req.Ip, LoginIP: req.Ip,
LoginTime: time.Now(), LoginTime: time.Now(),
DeviceInfo: req.DeviceId, DeviceInfo: req.DeviceId,

View File

@ -62,7 +62,7 @@ func newLoginService(serviceId int) *LoginService {
return nil return nil
} }
s.bindService = userBindService.NewUserBindService(model.UserRedis, s.ServiceEtcd()) s.bindService = userBindService.NewUserBindService(model.UserBindServiceRedis, s.ServiceEtcd())
s.processor = processor.NewProcessor() s.processor = processor.NewProcessor()
s.initProcessor() s.initProcessor()
s.OnInit() s.OnInit()