From eb417b0bfaf68c9548e8da87e042470b2fdec1fe Mon Sep 17 00:00:00 2001 From: zqj <582132116@qq.com> Date: Wed, 16 Feb 2022 18:31:37 +0800 Subject: [PATCH] reactor mongo --- actions/accountaction.go | 3 +-- actions/basic.go | 13 +++---------- actions/roleaction.go | 6 ++++-- actions/server.go | 4 ++-- components/db/mongo.go | 153 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------- components/db/redis.go | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------- conf/conf.go | 17 +++++++++++++---- conf/conf.yaml | 28 ++++++++++++---------------- models/account.go | 11 +++++------ models/basic.go | 46 ---------------------------------------------- models/hero.go | 30 ++++++++++++++++++++++++++++++ models/role.go | 35 ++++++++++++++++++++++------------- models/role_test.go | 30 +++++++++++++++--------------- 13 files changed, 231 insertions(+), 251 deletions(-) delete mode 100644 models/basic.go create mode 100644 models/hero.go diff --git a/actions/accountaction.go b/actions/accountaction.go index 84a970e..64fe323 100644 --- a/actions/accountaction.go +++ b/actions/accountaction.go @@ -10,7 +10,7 @@ import ( ) func (s *AccountServer) RegisterHandler(ctx context.Context, in *pb.Register) (*pb.PubRsp, error) { - ok, account := models.AccountExistByPhone(s.Database, in.Phone) + ok, account := models.AccountExistByPhone(s.DBName, in.Phone) if !ok { account.Phone = in.Phone account.Password = utils.Md5V(in.Password) @@ -24,7 +24,6 @@ func (s *AccountServer) RegisterHandler(ctx context.Context, in *pb.Register) (* return &pb.PubRsp{ Code: 0, }, nil - } func (s *AccountServer) CreateTokenHandler(ctx context.Context, in *pb.AccountInfo) (*pb.CreateTokenRsp, error) { diff --git a/actions/basic.go b/actions/basic.go index c72c036..b765cfb 100644 --- a/actions/basic.go +++ b/actions/basic.go @@ -3,27 +3,20 @@ package actions import ( "fmt" "net" - "pro2d/components/db" "pro2d/conf" - "pro2d/utils" ) type BasicServer struct { - Database *db.Database + DBName string } -func NewServer() *BasicServer { +func NewServer(db string) *BasicServer { return &BasicServer{ - Database: new(db.Database), + DBName: db, } } func (b *BasicServer) Start(sConf *conf.SConf) (net.Listener, error) { - if err := b.Database.Connect(sConf.MongoConf); err !=nil { - utils.Sugar.Debugf("db error: %v", err) - return nil, err - } - listing := fmt.Sprintf(":%d", sConf.Port) lis, err := net.Listen("tcp", listing) if err != nil { diff --git a/actions/roleaction.go b/actions/roleaction.go index 15fde3f..fd05cdd 100644 --- a/actions/roleaction.go +++ b/actions/roleaction.go @@ -43,7 +43,7 @@ func (s *GameServer) CreateRoleHandler(ctx context.Context, in *pb.Token) (*pb.R if account == nil { return nil, fmt.Errorf("1") } - ok, role := models.RoleExistByUid(s.Database, account.Uid) + ok, role := models.RoleExistByUid(account.Uid) if !ok { role.Role = &pb.Role{ Level: 0, @@ -67,13 +67,14 @@ func (s *GameServer) LoginHandler(ctx context.Context, in *pb.Token) (*pb.RoleRs if account == nil { return nil, fmt.Errorf("token is error") } - ok, role := models.RoleExistByUid(s.Database, account.Uid) + ok, role := models.RoleExistByUid(account.Uid) if !ok { return &pb.RoleRsp{ Rsp: &pb.PubRsp{ Code: -1, Msg: "role not exist", }, + }, nil } return &pb.RoleRsp{ @@ -82,5 +83,6 @@ func (s *GameServer) LoginHandler(ctx context.Context, in *pb.Token) (*pb.RoleRs Msg: "successful", }, Role: role.Role, + Hero: models.GetHeros(role.Heros), }, nil } diff --git a/actions/server.go b/actions/server.go index 936a0a9..b250d5b 100644 --- a/actions/server.go +++ b/actions/server.go @@ -16,7 +16,7 @@ type AccountServer struct{ func NewAccountServer() *AccountServer { return &AccountServer{ - BasicServer: NewServer(), + BasicServer: NewServer(conf.GlobalConf.AccountConf.DBName), } } @@ -60,7 +60,7 @@ type GameServer struct{ func NewGameServer() *GameServer { return &GameServer{ - BasicServer: NewServer(), + BasicServer: NewServer(conf.GlobalConf.GameConf.DBName), } } //拦截器 diff --git a/components/db/mongo.go b/components/db/mongo.go index 5f3b529..a9374c3 100644 --- a/components/db/mongo.go +++ b/components/db/mongo.go @@ -8,49 +8,47 @@ import ( "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "go.mongodb.org/mongo-driver/x/bsonx" - "pro2d/conf" "strconv" "time" ) -type Database struct { - Mongo *mongo.Database -} + +var MongoDBClient *mongo.Client //初始化 -func (db *Database)Connect(conf *conf.MongoConf) error { +func Connect(user, password, host string,port int, MaxNum int, timeOut int) error { var uri string - if conf.User!= "" { - uri = fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?w=majority", conf.User, conf.Password, conf.Host, conf.Port, conf.DBName) + if user!= "" { + //uri = fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?w=majority", conf.User, conf.Password, conf.Host, conf.Port, conf.DBName) + uri = fmt.Sprintf("mongodb://%s:%s@%s:%d/?w=majority", user, password, host, port) }else { - uri = fmt.Sprintf("mongodb://%s:%d/%s?w=majority", conf.Host, conf.Port, conf.DBName) + //uri = fmt.Sprintf("mongodb://%s:%d/%s?w=majority", conf.Host, conf.Port, conf.DBName) + uri = fmt.Sprintf("mongodb://%s:%d/?w=majority", host, port) } // 设置连接超时时间 - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(conf.TimeOut)) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeOut)) defer cancel() // 通过传进来的uri连接相关的配置 o := options.Client().ApplyURI(uri) // 设置最大连接数 - 默认是100 ,不设置就是最大 max 64 - o.SetMaxPoolSize(uint64(conf.MaxNum)) + o.SetMaxPoolSize(uint64(MaxNum)) // 发起链接 - client, err := mongo.Connect(ctx, o) + var err error + MongoDBClient, err = mongo.Connect(ctx, o) if err != nil { - fmt.Println("ConnectToDB", err) return err } // 判断服务是不是可用 - if err = client.Ping(context.Background(), readpref.Primary()); err != nil { - fmt.Println("ConnectToDB", err) + if err = MongoDBClient.Ping(context.Background(), readpref.Primary()); err != nil { return err } - - db.Mongo = client.Database(conf.DBName) return nil } -type MgoPool struct { - mgo *mongo.Database +type MgoColl struct { + mgo *mongo.Collection - collection string + pri interface{} + schema interface{} } func GetBsonD(key string, value interface{}) interface{} { @@ -60,58 +58,36 @@ func GetBsonM(key string, value interface{}) interface{} { return bson.M{key: value} } -func NewMongoPool(mgo *Database, collection string)*MgoPool { - return &MgoPool{ - mgo: mgo.Mongo, - collection: collection, +func NewMongoColl(database, collection string, pri, schema interface{}) *MgoColl { + return &MgoColl{ + mgo: MongoDBClient.Database(database).Collection(collection), + + pri: pri, + schema: schema, } } -func (m *MgoPool)SetDatabase(databases string) { +func (m *MgoColl)SetDatabase(databases string) { //m.db = databases } -func (m *MgoPool)SetCollect(coll string) { - m.collection = coll -} - -//func (m *MgoPool)Insert(coll string, buffer interface{}) error { -// _, err := m.mgo.Collection(coll).InsertOne(context.TODO(), buffer) -// if err != nil { -// fmt.Println(err) -// } -// return err -//} - -//func (m *MgoPool)FindOne(coll string, filter interface{}) (interface{}, error){ -// findOptions := options.FindOne() -// cur := m.MongoDBClient.Collection(coll).FindOne(context.TODO(), filter, findOptions) -// var role interface{} -// if err := cur.Decode(role); err != nil { -// return nil, err -// } -// return role, nil -//} // 查询单个 -func (m *MgoPool) FindOneKV(key string, value interface{}) *mongo.SingleResult { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) FindOneKV(key string, value interface{}) *mongo.SingleResult { //collection. filter := bson.D{ {key, value}} - singleResult := collection.FindOne(context.TODO(), filter) + singleResult := m.mgo.FindOne(context.TODO(), filter) return singleResult } -func (m *MgoPool) FindOne(pri interface{}) *mongo.SingleResult { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) FindOne(pri interface{}) *mongo.SingleResult { //collection. - singleResult := collection.FindOne(context.TODO(), pri) + singleResult := m.mgo.FindOne(context.TODO(), pri) return singleResult } //插入单个 -func (m *MgoPool) InsertOne(value interface{}) *mongo.InsertOneResult { - collection := m.mgo.Collection(m.collection) - insertResult, err := collection.InsertOne(context.TODO(), value) +func (m *MgoColl) InsertOne(value interface{}) *mongo.InsertOneResult { + insertResult, err := m.mgo.InsertOne(context.TODO(), value) if err != nil { fmt.Println(err) } @@ -119,28 +95,25 @@ func (m *MgoPool) InsertOne(value interface{}) *mongo.InsertOneResult { } //查询集合里有多少数据 -func (m *MgoPool) CollectionCount() (string, int64) { - collection := m.mgo.Collection(m.collection) - name := collection.Name() - size, _ := collection.EstimatedDocumentCount(context.TODO()) - return name, size +func (m *MgoColl) CollectionCount() (string, int64) { + size, _ := m.mgo.EstimatedDocumentCount(context.TODO()) + return m.mgo.Name(), size } //按选项查询集合 Skip 跳过 Limit 读取数量 sort 1 ,-1 . 1 为最初时间读取 , -1 为最新时间读取 -func (m *MgoPool) CollectionDocuments(Skip, Limit int64, sort int) *mongo.Cursor { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) CollectionDocuments(Skip, Limit int64, sort int) *mongo.Cursor { SORT := bson.D{ {"_id", sort}} //filter := bson.D{ {key,value}} filter := bson.D{ {}} findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip) //findOptions.SetLimit(i) - temp, _ := collection.Find(context.Background(), filter, findOptions) + temp, _ := m.mgo.Find(context.Background(), filter, findOptions) return temp } //获取集合创建时间和编号 -func (m *MgoPool) ParsingId(result string) (time.Time, uint64) { +func (m *MgoColl) ParsingId(result string) (time.Time, uint64) { temp1 := result[:8] timestamp, _ := strconv.ParseInt(temp1, 16, 64) dateTime := time.Unix(timestamp, 0) //这是截获情报时间 时间格式 2019-04-24 09:23:39 +0800 CST @@ -150,12 +123,11 @@ func (m *MgoPool) ParsingId(result string) (time.Time, uint64) { } //删除文章和查询文章 -func (m *MgoPool) DeleteAndFind(key string, value interface{}) (int64, *mongo.SingleResult) { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) DeleteAndFind(key string, value interface{}) (int64, *mongo.SingleResult) { filter := bson.D{ {key, value}} - singleResult := collection.FindOne(context.TODO(), filter) - DeleteResult, err := collection.DeleteOne(context.TODO(), filter, nil) + singleResult := m.mgo.FindOne(context.TODO(), filter) + DeleteResult, err := m.mgo.DeleteOne(context.TODO(), filter, nil) if err != nil { fmt.Println("删除时出现错误,你删不掉的~") } @@ -163,10 +135,9 @@ func (m *MgoPool) DeleteAndFind(key string, value interface{}) (int64, *mongo.Si } //删除文章 -func (m *MgoPool) Delete(key string, value interface{}) int64 { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) Delete(key string, value interface{}) int64 { filter := bson.D{ {key, value}} - count, err := collection.DeleteOne(context.TODO(), filter, nil) + count, err := m.mgo.DeleteOne(context.TODO(), filter, nil) if err != nil { fmt.Println(err) } @@ -175,11 +146,10 @@ func (m *MgoPool) Delete(key string, value interface{}) int64 { } //删除多个 -func (m *MgoPool) DeleteMany(key string, value interface{}) int64 { - collection := m.mgo.Collection(m.collection) +func (m *MgoColl) DeleteMany(key string, value interface{}) int64 { filter := bson.D{ {key, value}} - count, err := collection.DeleteMany(context.TODO(), filter) + count, err := m.mgo.DeleteMany(context.TODO(), filter) if err != nil { fmt.Println(err) } @@ -187,9 +157,8 @@ func (m *MgoPool) DeleteMany(key string, value interface{}) int64 { } //索引 -func (m *MgoPool) Index(key string){ - collection := m.mgo.Collection(m.collection) - collection.Indexes().CreateOne( +func (m *MgoColl) Index(key string){ + m.mgo.Indexes().CreateOne( context.Background(), mongo.IndexModel{ Keys : bsonx.Doc{{key, bsonx.Int32(1)}}, @@ -199,12 +168,11 @@ func (m *MgoPool) Index(key string){ } //更新&保存 -func (m *MgoPool) FindOneAndUpdate(filter interface{}, update interface{})*mongo.SingleResult { +func (m *MgoColl) FindOneAndUpdate(filter interface{}, update interface{})*mongo.SingleResult { //filter := bson.M{"name": "x", "array.name": "b"} //update := bson.M{"array.$[item].detail": "test"} - collection := m.mgo.Collection(m.collection) - res := collection.FindOneAndUpdate(context.Background(), + res := m.mgo.FindOneAndUpdate(context.Background(), filter, bson.M{"$set": update}) if res.Err() != nil { @@ -213,12 +181,33 @@ func (m *MgoPool) FindOneAndUpdate(filter interface{}, update interface{})*mongo return res } -func (m *MgoPool) UpdateOne(filter interface{}, update interface{})*mongo.UpdateResult { - collection := m.mgo.Collection(m.collection) - res, err := collection.UpdateOne(context.TODO(), filter, update) +func (m *MgoColl) UpdateOne(filter interface{}, update interface{})*mongo.UpdateResult { + res, err := m.mgo.UpdateOne(context.TODO(), filter, update) if err != nil { return nil } return res +} + + +func (m *MgoColl) Load() error{ + r := m.FindOne(m.pri) + err := r.Decode(m.schema) + if err != nil { + return err + } + return nil +} + +func (m *MgoColl) Create() { + m.InsertOne(m.schema) +} + +func (m *MgoColl) Update(update interface{}) { + m.FindOneAndUpdate(m.pri, update) +} + +func (m *MgoColl)Save() { + m.FindOneAndUpdate(m.pri, m.schema) } \ No newline at end of file diff --git a/components/db/redis.go b/components/db/redis.go index 4b73e4c..6fbd124 100644 --- a/components/db/redis.go +++ b/components/db/redis.go @@ -1,54 +1,54 @@ package db - -import ( - "fmt" - "github.com/garyburd/redigo/redis" - "pro2d/conf" - "pro2d/utils" - "time" -) - -type RedisPool struct { - RedisPool *redis.Pool -} - -func (rp *RedisPool)Connect(conf *conf.ServerConf) error { - rp.RedisPool = &redis.Pool{ - //最大活跃连接数,0代表无限 - MaxActive: 888, - MaxIdle: 20, - //闲置连接的超时时间 - IdleTimeout: time.Second * 100, - //定义拨号获得连接的函数 - Dial: func() (redis.Conn, error) { - option := []redis.DialOption{redis.DialDatabase(conf.RedisConf.DB)} - if conf.RedisConf.Auth != "" { - option = append(option, redis.DialPassword(conf.RedisConf.Auth)) - } - return redis.Dial("tcp",conf.RedisConf.Address, option...) - }, - } - return nil -} - -func (rp *RedisPool)Close() { - rp.RedisPool.Close() -} - -func (rp *RedisPool) Insert() error { - conn := rp.RedisPool.Get() - defer conn.Close() - reply, err := conn.Do("HKEYS", fmt.Sprintf("account:%s", "123123")) - if err != nil { - return err - } - - utils.Sugar.Debugf("%v", reply) - reply, err = conn.Do("HMSET", fmt.Sprintf("account:%s", "1231231"), "phone", "1231231", "passwd", "2131231") - if err != nil { - utils.Sugar.Errorf("%v", err) - return err - } - utils.Sugar.Debugf("%v", reply) - return nil -} +// +//import ( +// "fmt" +// "github.com/garyburd/redigo/redis" +// "pro2d/conf" +// "pro2d/utils" +// "time" +//) +// +//type RedisPool struct { +// RedisPool *redis.Pool +//} +// +//func (rp *RedisPool)Connect(conf *conf.ServerConf) error { +// rp.RedisPool = &redis.Pool{ +// //最大活跃连接数,0代表无限 +// MaxActive: 888, +// MaxIdle: 20, +// //闲置连接的超时时间 +// IdleTimeout: time.Second * 100, +// //定义拨号获得连接的函数 +// Dial: func() (redis.Conn, error) { +// option := []redis.DialOption{redis.DialDatabase(conf.RedisConf.DB)} +// if conf.RedisConf.Auth != "" { +// option = append(option, redis.DialPassword(conf.RedisConf.Auth)) +// } +// return redis.Dial("tcp",conf.RedisConf.Address, option...) +// }, +// } +// return nil +//} +// +//func (rp *RedisPool)Close() { +// rp.RedisPool.Close() +//} +// +//func (rp *RedisPool) Insert() error { +// conn := rp.RedisPool.Get() +// defer conn.Close() +// reply, err := conn.Do("HKEYS", fmt.Sprintf("account:%s", "123123")) +// if err != nil { +// return err +// } +// +// utils.Sugar.Debugf("%v", reply) +// reply, err = conn.Do("HMSET", fmt.Sprintf("account:%s", "1231231"), "phone", "1231231", "passwd", "2131231") +// if err != nil { +// utils.Sugar.Errorf("%v", err) +// return err +// } +// utils.Sugar.Debugf("%v", reply) +// return nil +//} diff --git a/conf/conf.go b/conf/conf.go index 107cf68..4841a5e 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -5,6 +5,7 @@ import ( lumberjack "gopkg.in/natefinch/lumberjack.v2" "gopkg.in/yaml.v3" "io/ioutil" + "pro2d/components/db" "pro2d/utils" ) @@ -27,7 +28,6 @@ type MongoConf struct { Password string `yaml:"password"` Host string `yaml:"host"` Port int `yaml:"port"` - DBName string `yaml:"dbname"` TimeOut int `yaml:"timeout"` MaxNum int `yaml:"maxnum"` } @@ -36,7 +36,7 @@ type SConf struct { Name string `yaml:"name"` IP string `yaml:"ip"` Port int `yaml:"port"` - MongoConf *MongoConf `yaml:"mongo"` + DBName string `yaml:"dbname"` } type ServerConf struct { @@ -44,6 +44,7 @@ type ServerConf struct { Name string `yaml:"name"` WorkerID int64 `yaml:"workerid"` DatacenterID int64 `yaml:"datacenterid"` + MongoConf *MongoConf `yaml:"mongo"` AccountConf *SConf `yaml:"server_account"` GameConf *SConf `yaml:"server_game"` RedisConf *RedisConf `yaml:"redis"` @@ -51,8 +52,10 @@ type ServerConf struct { Etcd *Etcd `yaml:"etcd"` } -var GlobalConf ServerConf -var SnowFlack *utils.Snowflake +var( + GlobalConf ServerConf + SnowFlack *utils.Snowflake +) func init() { configFile, err := ioutil.ReadFile("conf/conf.yaml") if err != nil { @@ -70,4 +73,10 @@ func init() { //初始化雪花算法 SnowFlack = utils.NewSnowflake(GlobalConf.WorkerID, GlobalConf.DatacenterID) + + //初始化数据库 + err = db.Connect(GlobalConf.MongoConf.User, GlobalConf.MongoConf.Password, GlobalConf.MongoConf.Host, GlobalConf.MongoConf.Port, GlobalConf.MongoConf.MaxNum, GlobalConf.MongoConf.TimeOut) + if err != nil { + utils.Sugar.Errorf("mongodb init error: %v", err) + } } \ No newline at end of file diff --git a/conf/conf.yaml b/conf/conf.yaml index 9a59c94..e0c551b 100644 --- a/conf/conf.yaml +++ b/conf/conf.yaml @@ -2,30 +2,26 @@ develop: true name: "Pro2DServer" workerid: 1 datacenterid: 1 + +mongo: &default-mongo + host: "192.168.0.206" + port: 27017 + user: "" + password: "" + timeout: 2 + maxnum: 50 + server_account: name: "account" ip: "192.168.0.206" port: 8848 - mongo: - host: "192.168.0.206" - port: 27017 - user: "" - password: "" - dbname: "account" - timeout: 2 - maxnum: 50 + dbname: "account" + server_game: name: "game" ip: "192.168.0.206" port: 8849 - mongo: - host: "192.168.0.206" - port: 27017 - user: "" - password: "" - dbname: "game" - timeout: 2 - maxnum: 50 + dbname: "game" logconf: filename: "./pro2d.log" # ⽇志⽂件路径 diff --git a/models/account.go b/models/account.go index b5f3cb3..3e8549c 100644 --- a/models/account.go +++ b/models/account.go @@ -6,27 +6,26 @@ import ( ) type AccountModel struct { - *ModelBaseMgo + *db.MgoColl *pb.AccountInfo } -func AccountExistByPhone(mgo *db.Database, phone string) (bool, *AccountModel){ - m := NewAccount(mgo, phone) +func AccountExistByPhone(database, phone string) (bool, *AccountModel){ + m := NewAccount(database, phone) if err := m.Load(); err != nil { return false, m } return true, m } -func NewAccount(mgo *db.Database, phone string) *AccountModel { +func NewAccount(database, phone string) *AccountModel { ac := &pb.AccountInfo{ Phone: phone, } account := &AccountModel{ - ModelBaseMgo: NewModelBaseMgo(mgo, "account", db.GetBsonM("phone", phone), ac), + MgoColl: db.NewMongoColl(database, "account", db.GetBsonM("phone", phone), ac), AccountInfo: ac, } - return account } \ No newline at end of file diff --git a/models/basic.go b/models/basic.go deleted file mode 100644 index 89ecc36..0000000 --- a/models/basic.go +++ /dev/null @@ -1,46 +0,0 @@ -package models - -import ( - "pro2d/components/db" -) - -type ModelBaseMgo struct { - MonGo *db.MgoPool - - pri interface{} - schema interface{} -} - - -func NewModelBaseMgo(mgo *db.Database, collection string, pri interface{}, schema interface{}) *ModelBaseMgo{ - return &ModelBaseMgo{ - MonGo: db.NewMongoPool(mgo, collection), - pri: pri, - schema: schema, - } -} - -func (base *ModelBaseMgo) Load() error{ - r := base.MonGo.FindOne(base.pri) - err := r.Decode(base.schema) - if err != nil { - return err - } - return nil -} - -func (base *ModelBaseMgo) Create() { - base.MonGo.InsertOne(base.schema) -} - -func (base *ModelBaseMgo) Index(key string) { - base.MonGo.Index(key) -} - -func (base *ModelBaseMgo) Update(update interface{}) { - base.MonGo.FindOneAndUpdate(base.pri, update) -} - -func (base *ModelBaseMgo) Save() { - base.MonGo.FindOneAndUpdate(base.pri, base.schema) -} \ No newline at end of file diff --git a/models/hero.go b/models/hero.go new file mode 100644 index 0000000..41fc261 --- /dev/null +++ b/models/hero.go @@ -0,0 +1,30 @@ +package models + +import ( + "pro2d/components/db" + "pro2d/conf" + "pro2d/protos/pb" +) + +type HeroModel struct { + *db.MgoColl + Hero *pb.Hero +} +type HeroMap map[string]*HeroModel + +func GetHeros(hm HeroMap) map[string]*pb.Hero { + h := make(map[string]*pb.Hero) + for k, v := range hm { + h[k] = v.Hero + } + return h +} + +func NewHero(h *pb.Hero) *HeroModel { + m := &HeroModel{ + MgoColl: db.NewMongoColl(conf.GlobalConf.GameConf.DBName, "hero", db.GetBsonM("id", h.Id), h), + Hero: h, + } + m.Load() + return m +} diff --git a/models/role.go b/models/role.go index 71d5a4b..0bc816d 100644 --- a/models/role.go +++ b/models/role.go @@ -1,34 +1,34 @@ package models import ( + "fmt" "pro2d/components/db" + "pro2d/conf" "pro2d/protos/pb" ) type RoleModel struct { - *ModelBaseMgo - *pb.Role + *db.MgoColl + Role *pb.Role + Heros HeroMap + Teams *pb.Team + Equip *pb.Equipment + Prop *pb.Prop } -//创建数据 -//数据加载 -//数据保存 - -func RoleExistByUid(mgo *db.Database, uid int64) (bool, *RoleModel){ - m := NewRole(mgo, uid) +func RoleExistByUid(uid int64) (bool, *RoleModel){ + m := NewRole(&pb.Role{Uid: uid}) if err := m.Load(); err != nil { return false, m } return true, m } -func NewRole(mgo *db.Database, uid int64) *RoleModel { - r := &pb.Role{ - Uid: uid, - } +func NewRole(r *pb.Role) *RoleModel { m := &RoleModel{ - ModelBaseMgo: NewModelBaseMgo(mgo, "role", db.GetBsonM("uid", uid), r), + MgoColl: db.NewMongoColl(conf.GlobalConf.GameConf.DBName, "role", db.GetBsonM("uid", r.Uid), r), Role: r, + Heros: make(HeroMap), } m.Load() return m @@ -36,3 +36,12 @@ func NewRole(mgo *db.Database, uid int64) *RoleModel { func (m *RoleModel) LoadAll() { } + +func (m *RoleModel) LoadHero() { +} + +func (m *RoleModel) AddHero(hero *pb.Hero) { + h := NewHero(hero) + h.Create() + m.Heros[fmt.Sprintf("%d%d", m.Role.Id, h.Hero.Id)] = h +} \ No newline at end of file diff --git a/models/role_test.go b/models/role_test.go index f463aa3..14a1e86 100644 --- a/models/role_test.go +++ b/models/role_test.go @@ -1,31 +1,31 @@ package models import ( - "pro2d/components/db" - "pro2d/conf" - "pro2d/utils" + "pro2d/protos/pb" "testing" - "time" ) func TestNewRole(t *testing.T) { - db := &db.Database{} - if err := db.Connect(conf.GlobalConf.GameConf.MongoConf); err != nil { - utils.Sugar.Errorf("%v", err) - return - } - + //db.MongoDBClient.Database(conf.GlobalConf.AccountConf.DBName).Drop(context.Background()) + //db.MongoDBClient.Database(conf.GlobalConf.GameConf.DBName).Drop(context.Background()) - //db.Mongo.Drop(context.Background()) var uid int64 = 1 var role *RoleModel - if ok, role := RoleExistByUid(db, uid); ok { + if ok, role := RoleExistByUid(uid); ok { role.Role.Device = "111111" - role.Role.LoginTime = time.Now().Unix() + role.AddHero(&pb.Hero{ + Id: 1, + RoleId: role.Role.Id, + Type: 0, + Level: 0, + ReinCount: 0, + ReinPoint: 0, + Equipments: "", + }) role.Save() }else { - role = NewRole(db, uid) - role.Role.Id = "1" + role = NewRole(&pb.Role{Uid: uid}) + role.Role.Id = 1 role.Role.Device = "222222" role.Role.Level = 0 role.Create() -- libgit2 0.21.2