Commit 33ea26abaec01e8c0c191152e886fc11a0bd5c5a

Authored by zhangqijia
1 parent 6f0d72bd

使用schema封装mongo

@@ -9,14 +9,14 @@ gen: @@ -9,14 +9,14 @@ gen:
9 test: 9 test:
10 go run test/client.go 10 go run test/client.go
11 http: 11 http:
12 - go run cmd/http.go 12 + go run -race cmd/http.go
13 13
14 game: 14 game:
15 - go run cmd/game.go 15 + go run -race cmd/game.go
16 build: 16 build:
17 - go build -o bin/account cmd/http.go  
18 - go build -o bin/game cmd/game.go  
19 - go build -o bin/test test/client.go 17 + go build -race -o bin/account cmd/http.go
  18 + go build -race -o bin/game cmd/game.go
  19 + go build -race -o bin/test test/client.go
20 regame:plugin 20 regame:plugin
21 lsof -i:8849 | grep "game" | grep -v grep | awk '{print $$2}' | xargs -I {} kill -USR1 {} 21 lsof -i:8849 | grep "game" | grep -v grep | awk '{print $$2}' | xargs -I {} kill -USR1 {}
22 22
src/actions/AccountAction.go
@@ -26,7 +26,7 @@ func (h *AccountAction) Register(c *gin.Context) (int, interface{}){ @@ -26,7 +26,7 @@ func (h *AccountAction) Register(c *gin.Context) (int, interface{}){
26 26
27 account.Uid = conf.SnowFlack.NextValStr() 27 account.Uid = conf.SnowFlack.NextValStr()
28 account.Password = utils.Md5V(register.Password) 28 account.Password = utils.Md5V(register.Password)
29 - if _, err := account.Create(); err != nil{ 29 + if err := account.Create(); err != nil{
30 return -3, "account register err: " + err.Error() 30 return -3, "account register err: " + err.Error()
31 } 31 }
32 account.Password = register.Password 32 account.Password = register.Password
src/common/common.go
@@ -16,6 +16,6 @@ const ( @@ -16,6 +16,6 @@ const (
16 WheelSize = 3600 16 WheelSize = 3600
17 17
18 //心跳 18 //心跳
19 - HEART_TIMER_INTERVAL = 5 //s  
20 - HEART_TIMEOUT_COUNT_MAX = 20 //最大超时次数 19 + HeartTimerInterval = 5 //s
  20 + HeartTimeoutCountMax = 20 //最大超时次数
21 ) 21 )
src/components/db/mongo.go
@@ -76,8 +76,7 @@ func SetUnique(collection string, key string) (string, error) { @@ -76,8 +76,7 @@ func SetUnique(collection string, key string) (string, error) {
76 type MgoColl struct { 76 type MgoColl struct {
77 collection *mongo.Collection 77 collection *mongo.Collection
78 78
79 - pri interface{}  
80 - schema interface{} 79 + schema *Schema
81 } 80 }
82 81
83 func GetBsonD(key string, value interface{}) interface{} { 82 func GetBsonD(key string, value interface{}) interface{} {
@@ -87,10 +86,9 @@ func GetBsonM(key string, value interface{}) interface{} { @@ -87,10 +86,9 @@ func GetBsonM(key string, value interface{}) interface{} {
87 return bson.M{key: value} 86 return bson.M{key: value}
88 } 87 }
89 88
90 -func NewMongoColl(key string, schema interface{}) *MgoColl { 89 +func NewMongoColl(schema *Schema) *MgoColl {
91 return &MgoColl{ 90 return &MgoColl{
92 - collection: MongoDatabase.Collection(utils.GetCollName(schema)),  
93 - pri: GetBsonM(utils.GetPriKey(schema), key), 91 + collection: MongoDatabase.Collection(schema.GetCollName()),
94 schema: schema, 92 schema: schema,
95 } 93 }
96 } 94 }
@@ -196,7 +194,7 @@ func (m *MgoColl) FindOneAndUpdate(filter interface{}, update interface{})*mongo @@ -196,7 +194,7 @@ func (m *MgoColl) FindOneAndUpdate(filter interface{}, update interface{})*mongo
196 } 194 }
197 195
198 func (m *MgoColl) UpdateOne(filter interface{}, update interface{})*mongo.UpdateResult { 196 func (m *MgoColl) UpdateOne(filter interface{}, update interface{})*mongo.UpdateResult {
199 - res, err := m.collection.UpdateOne(context.TODO(), filter, update) 197 + res, err := m.collection.UpdateOne(context.TODO(), filter, bson.D{{"$set", update}})
200 if err != nil { 198 if err != nil {
201 return nil 199 return nil
202 } 200 }
@@ -204,10 +202,9 @@ func (m *MgoColl) UpdateOne(filter interface{}, update interface{})*mongo.Update @@ -204,10 +202,9 @@ func (m *MgoColl) UpdateOne(filter interface{}, update interface{})*mongo.Update
204 return res 202 return res
205 } 203 }
206 204
207 -  
208 func (m *MgoColl) Load() error{ 205 func (m *MgoColl) Load() error{
209 - r := m.collection.FindOne(context.TODO(), m.pri)  
210 - err := r.Decode(m.schema) 206 + r := m.collection.FindOne(context.TODO(), m.schema.GetPri())
  207 + err := r.Decode(m.schema.GetSchema())
211 if err != nil { 208 if err != nil {
212 return err 209 return err
213 } 210 }
@@ -215,17 +212,13 @@ func (m *MgoColl) Load() error{ @@ -215,17 +212,13 @@ func (m *MgoColl) Load() error{
215 } 212 }
216 213
217 func (m *MgoColl) Create() (*mongo.InsertOneResult, error){ 214 func (m *MgoColl) Create() (*mongo.InsertOneResult, error){
218 - return m.collection.InsertOne(context.TODO(), m.schema)  
219 -}  
220 -  
221 -func (m *MgoColl) Update(update interface{}) {  
222 - m.FindOneAndUpdate(m.pri, update) 215 + return m.collection.InsertOne(context.TODO(), m.schema.GetSchema())
223 } 216 }
224 217
225 func (m *MgoColl) UpdateProperty(key string, val interface{}) { 218 func (m *MgoColl) UpdateProperty(key string, val interface{}) {
226 - m.FindOneAndUpdate(m.pri, bson.M{strings.ToLower(key): val}) 219 + m.UpdateOne(m.schema.GetPri(), bson.M{strings.ToLower(key): val})
227 } 220 }
228 221
229 -func (m *MgoColl)Save() {  
230 - m.FindOneAndUpdate(m.pri, m.schema)  
231 -}  
232 \ No newline at end of file 222 \ No newline at end of file
  223 +func (m *MgoColl) UpdateProperties(properties map[string]interface{}) {
  224 + m.UpdateOne(m.schema.GetPri(), properties)
  225 +}
src/components/db/schema.go
@@ -6,38 +6,74 @@ import ( @@ -6,38 +6,74 @@ import (
6 ) 6 )
7 7
8 type Schema struct { 8 type Schema struct {
9 - reflect.Type 9 + mgo *MgoColl
  10 + reflectValue *reflect.Value
  11 + reflectType reflect.Type
  12 +
  13 +
10 pri interface{} 14 pri interface{}
11 schema interface{} 15 schema interface{}
12 } 16 }
13 17
14 -func NewSchema(pri, schema interface{}) *Schema {  
15 - s := reflect.TypeOf(schema) 18 +func NewSchema(key string, schema interface{}) *Schema {
  19 + s := reflect.ValueOf(schema)
16 if s.Kind() == reflect.Ptr { 20 if s.Kind() == reflect.Ptr {
17 - s = reflect.TypeOf(s).Elem() 21 + s = reflect.ValueOf(schema).Elem()
18 } 22 }
19 - return &Schema{  
20 - Type: s,  
21 - pri: pri, 23 + sch := &Schema{
  24 + reflectValue: &s,
  25 + reflectType: s.Type(),
22 schema: schema, 26 schema: schema,
23 } 27 }
  28 + sch.mgo = NewMongoColl(sch)
  29 + sch.pri = GetBsonD(sch.getPriTag(), key)
  30 + return sch
24 } 31 }
25 32
26 -func (s *Schema)GetSchemaType() reflect.Type {  
27 - return s.Type 33 +func (s *Schema) GetSchemaType() reflect.Type {
  34 + return s.reflectType
28 } 35 }
29 36
30 -func (s *Schema)GetCollName() string { 37 +func (s *Schema) GetCollName() string {
31 return strings.ToLower(s.GetSchemaType().Name()) 38 return strings.ToLower(s.GetSchemaType().Name())
32 } 39 }
33 40
34 -func (s *Schema)GetPriKey() string { 41 +func (s *Schema) getPriTag() string {
35 var pri string 42 var pri string
36 - for i := 0; i < s.NumField(); i++ {  
37 - if s.Field(i).Tag.Get("pri") == "1" {  
38 - pri = strings.ToLower(s.Field(i).Name) 43 + for i := 0; i < s.reflectType.NumField(); i++ {
  44 + if s.reflectType.Field(i).Tag.Get("pri") == "1" {
  45 + pri = strings.ToLower(s.reflectType.Field(i).Name)
39 break 46 break
40 } 47 }
41 } 48 }
42 return pri 49 return pri
43 } 50 }
  51 +
  52 +func (s *Schema) GetPri() interface{} {
  53 + return s.pri
  54 +}
  55 +
  56 +func (s *Schema) GetSchema() interface{} {
  57 + return s.schema
  58 +}
  59 +
  60 +func (s *Schema) Load() error {
  61 + return s.mgo.Load()
  62 +}
  63 +
  64 +func (s *Schema) Create() error {
  65 + _, err := s.mgo.Create()
  66 + return err
  67 +}
  68 +
  69 +func (s *Schema) UpdateProperty(key string, val interface{}) {
  70 + s.reflectValue.FieldByName(key).Set(reflect.ValueOf(val))
  71 + s.mgo.UpdateProperty(key, val)
  72 +}
  73 +
  74 +func (s *Schema) UpdateProperties(properties map[string]interface{}) {
  75 + for key, val := range properties {
  76 + s.reflectValue.FieldByName(key).Set(reflect.ValueOf(val))
  77 + }
  78 + s.mgo.UpdateProperties(properties)
  79 +}
src/components/jwt/jwt.go deleted
@@ -1,96 +0,0 @@ @@ -1,96 +0,0 @@
1 -package jwt  
2 -  
3 -import (  
4 - "context"  
5 - "fmt"  
6 - "pro2d/src/common"  
7 - "pro2d/src/components/logger"  
8 - "time"  
9 -  
10 - jwt "github.com/dgrijalva/jwt-go"  
11 - "google.golang.org/grpc/metadata"  
12 -)  
13 -  
14 -func CreateToken(uid string) (tokenString string) {  
15 - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{  
16 - "iss": "pro2d-app-server",  
17 - "aud": "pro2d-app-server",  
18 - "nbf": time.Now().Unix(),  
19 - "exp": time.Now().Add(time.Hour).Unix(),  
20 - "sub": "pro2d",  
21 - "uid": uid,  
22 - })  
23 - tokenString, err := token.SignedString([]byte(common.Pro2DTokenSignedString))  
24 - if err != nil {  
25 - panic(err)  
26 - }  
27 - return tokenString  
28 -}  
29 -  
30 -func ParseToken(tokenStr string) string {  
31 - var clientClaims Claims  
32 - token, err := jwt.ParseWithClaims(tokenStr, &clientClaims, func(token *jwt.Token) (interface{}, error) {  
33 - if token.Header["alg"] != "HS256" {  
34 - //panic("ErrInvalidAlgorithm")  
35 - logger.Error("ErrInvalidAlgorithm")  
36 - return nil, nil  
37 - }  
38 - return []byte(common.Pro2DTokenSignedString), nil  
39 - })  
40 - if err != nil {  
41 - logger.Error("jwt parse error")  
42 - return ""  
43 - }  
44 -  
45 - if !token.Valid {  
46 - logger.Error("ErrInvalidToken")  
47 - return ""  
48 - }  
49 - return clientClaims.Uid  
50 -}  
51 -  
52 -  
53 -// Claims defines the struct containing the token claims.  
54 -type Claims struct {  
55 - jwt.StandardClaims  
56 - Uid string  
57 -}  
58 -  
59 -// 从 context 的 metadata 中,取出 token  
60 -func getTokenFromContext(ctx context.Context) (string, error) {  
61 - md, ok := metadata.FromIncomingContext(ctx)  
62 - if !ok {  
63 - return "", fmt.Errorf("ErrNoMetadataInContext")  
64 - }  
65 - // md 的类型是 type MD map[string][]string  
66 - token, ok := md["authorization"]  
67 - if !ok || len(token) == 0 {  
68 - return "", fmt.Errorf("ErrNoAuthorizationInMetadata")  
69 - }  
70 - // 因此,token 是一个字符串数组,我们只用了 token[0]  
71 - return token[0], nil  
72 -}  
73 -  
74 -func CheckAuth(ctx context.Context) string {  
75 - tokenStr, err := getTokenFromContext(ctx)  
76 - if err != nil {  
77 - logger.Error("get token from context error")  
78 - return ""  
79 - }  
80 - return ParseToken(tokenStr)  
81 -}  
82 -  
83 -// AuthToken 自定义认证 客户端使用  
84 -type AuthToken struct {  
85 - Token string  
86 -}  
87 -  
88 -func (c AuthToken) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {  
89 - return map[string]string{  
90 - "authorization": c.Token,  
91 - }, nil  
92 -}  
93 -  
94 -func (c AuthToken) RequireTransportSecurity() bool {  
95 - return false  
96 -}  
97 \ No newline at end of file 0 \ No newline at end of file
src/components/jwt/jwt_test.go deleted
@@ -1,18 +0,0 @@ @@ -1,18 +0,0 @@
1 -package jwt  
2 -  
3 -import (  
4 - "fmt"  
5 - "pro2d/protos/pb"  
6 - "testing"  
7 -)  
8 -  
9 -func TestCreateToken(t *testing.T) {  
10 - account := &pb.Account{  
11 - Phone: "17683852936",  
12 - Password: "123456",  
13 - Uid: "12312",  
14 - }  
15 - token := CreateToken(account.Uid)  
16 - ac := ParseToken(token)  
17 - fmt.Println("token: ", token, "\nac: ", ac)  
18 -}  
src/components/net/conn.go
@@ -28,7 +28,6 @@ type Connection struct { @@ -28,7 +28,6 @@ type Connection struct {
28 writer *bufio.Writer 28 writer *bufio.Writer
29 29
30 WBuffer chan []byte 30 WBuffer chan []byte
31 - RBuffer chan *MsgPkg  
32 31
33 Quit chan *Connection 32 Quit chan *Connection
34 33
@@ -52,7 +51,6 @@ func NewConn(id int, conn net.Conn, s *Server) *Connection { @@ -52,7 +51,6 @@ func NewConn(id int, conn net.Conn, s *Server) *Connection {
52 scanner: bufio.NewScanner(conn), 51 scanner: bufio.NewScanner(conn),
53 writer: bufio.NewWriter(conn), 52 writer: bufio.NewWriter(conn),
54 WBuffer: make(chan []byte), 53 WBuffer: make(chan []byte),
55 - RBuffer: make(chan *MsgPkg),  
56 Quit: make(chan *Connection), 54 Quit: make(chan *Connection),
57 lastHeartCheckTime: utils.Timex(), 55 lastHeartCheckTime: utils.Timex(),
58 heartTimeoutCount: 0, 56 heartTimeoutCount: 0,
@@ -99,18 +97,16 @@ func (c *Connection) read() { @@ -99,18 +97,16 @@ func (c *Connection) read() {
99 97
100 if err := c.scanner.Err(); err != nil { 98 if err := c.scanner.Err(); err != nil {
101 fmt.Printf("scanner.err: %s\n", err.Error()) 99 fmt.Printf("scanner.err: %s\n", err.Error())
102 - c.Quiting()  
103 return 100 return
104 } 101 }
105 } 102 }
106 103
107 -  
108 func (c *Connection) checkHeartBeat(now int64) { 104 func (c *Connection) checkHeartBeat(now int64) {
109 lastHeartCheckTime := atomic.LoadInt64(&c.lastHeartCheckTime) 105 lastHeartCheckTime := atomic.LoadInt64(&c.lastHeartCheckTime)
110 logger.Debug("checkHeartBeat ID: %d, last: %d, now: %d", c.Id, lastHeartCheckTime, now) 106 logger.Debug("checkHeartBeat ID: %d, last: %d, now: %d", c.Id, lastHeartCheckTime, now)
111 - if math.Abs(float64(lastHeartCheckTime - now)) > common.HEART_TIMER_INTERVAL { 107 + if math.Abs(float64(lastHeartCheckTime - now)) > common.HeartTimerInterval {
112 c.heartTimeoutCount++ 108 c.heartTimeoutCount++
113 - if c.heartTimeoutCount >= common.HEART_TIMEOUT_COUNT_MAX { 109 + if c.heartTimeoutCount >= common.HeartTimeoutCountMax {
114 c.Quiting() 110 c.Quiting()
115 return 111 return
116 } 112 }
@@ -125,31 +121,18 @@ func (c *Connection) update() { @@ -125,31 +121,18 @@ func (c *Connection) update() {
125 now := utils.Timex() 121 now := utils.Timex()
126 if now >= nextCheckTime { 122 if now >= nextCheckTime {
127 c.checkHeartBeat(now) 123 c.checkHeartBeat(now)
128 - nextCheckTime = now + common.HEART_TIMER_INTERVAL 124 + nextCheckTime = now + common.HeartTimerInterval
129 atomic.StoreInt64(&c.nextCheckTime, nextCheckTime) 125 atomic.StoreInt64(&c.nextCheckTime, nextCheckTime)
130 } 126 }
131 } 127 }
132 -//  
133 -//func (c *Connection) SetLastHeartCheckTime() {  
134 -// now := utils.Timex()  
135 -// lastHeartCheckTime := atomic.LoadInt64(&c.lastHeartCheckTime)  
136 -// if now - lastHeartCheckTime < common.HEART_TIMER_INTERVAL {  
137 -// logger.Debug("heart too quick")  
138 -// }  
139 -// atomic.StoreInt64(&c.lastHeartCheckTime, now)  
140 -//} 128 +
141 129
142 func (c *Connection) Start() { 130 func (c *Connection) Start() {
143 go c.write() 131 go c.write()
144 go c.read() 132 go c.read()
145 - //for {  
146 - // c.SendMsgByCode(100, 1, nil)  
147 - // time.Sleep(2*time.Second)  
148 - //}  
149 } 133 }
150 134
151 func (c *Connection) Stop() { 135 func (c *Connection) Stop() {
152 - close(c.RBuffer)  
153 c.Conn.Close() 136 c.Conn.Close()
154 } 137 }
155 138
src/components/timewheel/timerwheel.go
@@ -99,7 +99,7 @@ func NewTimeWheel() *TimeWheel { @@ -99,7 +99,7 @@ func NewTimeWheel() *TimeWheel {
99 99
100 func (tw *TimeWheel) add(t *timer) bool { 100 func (tw *TimeWheel) add(t *timer) bool {
101 time := t.expiration 101 time := t.expiration
102 - currentTime := tw.time 102 + currentTime := atomic.LoadUint32(&tw.time)
103 if time <= currentTime { 103 if time <= currentTime {
104 return false 104 return false
105 } 105 }
@@ -136,8 +136,7 @@ func (tw *TimeWheel) moveList(level, idx int) { @@ -136,8 +136,7 @@ func (tw *TimeWheel) moveList(level, idx int) {
136 136
137 func (tw *TimeWheel) shift() { 137 func (tw *TimeWheel) shift() {
138 mask := TimeNear 138 mask := TimeNear
139 - tw.time++  
140 - ct := tw.time 139 + ct := atomic.AddUint32(&tw.time, 1)
141 if ct == 0 { 140 if ct == 0 {
142 tw.moveList(3, 0) 141 tw.moveList(3, 0)
143 }else { 142 }else {
src/models/account.go
@@ -6,7 +6,7 @@ import ( @@ -6,7 +6,7 @@ import (
6 ) 6 )
7 7
8 type AccountModel struct { 8 type AccountModel struct {
9 - *db.MgoColl 9 + *db.Schema
10 *pb.Account 10 *pb.Account
11 } 11 }
12 12
@@ -23,7 +23,7 @@ func NewAccount(phone string) *AccountModel { @@ -23,7 +23,7 @@ func NewAccount(phone string) *AccountModel {
23 Phone: phone, 23 Phone: phone,
24 } 24 }
25 account := &AccountModel{ 25 account := &AccountModel{
26 - MgoColl: db.NewMongoColl(phone, ac), 26 + Schema: db.NewSchema(phone, ac),
27 Account: ac, 27 Account: ac,
28 } 28 }
29 29
src/models/equip.go
@@ -3,20 +3,19 @@ package models @@ -3,20 +3,19 @@ package models
3 import ( 3 import (
4 "pro2d/protos/pb" 4 "pro2d/protos/pb"
5 "pro2d/src/components/db" 5 "pro2d/src/components/db"
6 - "strconv"  
7 ) 6 )
8 7
9 type EquipModels struct { 8 type EquipModels struct {
10 - *db.MgoColl 9 + *db.Schema
11 Equip *pb.Equipment 10 Equip *pb.Equipment
12 } 11 }
13 12
14 -func NewEquip(id int64) *EquipModels { 13 +func NewEquip(id string) *EquipModels {
15 data := &pb.Equipment{ 14 data := &pb.Equipment{
16 Id: id, 15 Id: id,
17 } 16 }
18 m := &EquipModels{ 17 m := &EquipModels{
19 - MgoColl: db.NewMongoColl(strconv.Itoa(int(id)), data), 18 + Schema: db.NewSchema(id, data),
20 Equip: data, 19 Equip: data,
21 } 20 }
22 21
src/models/hero.go
@@ -3,11 +3,10 @@ package models @@ -3,11 +3,10 @@ package models
3 import ( 3 import (
4 "pro2d/protos/pb" 4 "pro2d/protos/pb"
5 "pro2d/src/components/db" 5 "pro2d/src/components/db"
6 - "strconv"  
7 ) 6 )
8 7
9 type HeroModel struct { 8 type HeroModel struct {
10 - *db.MgoColl 9 + *db.Schema
11 Hero *pb.Hero 10 Hero *pb.Hero
12 } 11 }
13 type HeroMap map[string]*HeroModel 12 type HeroMap map[string]*HeroModel
@@ -20,12 +19,12 @@ func GetHeros(hm HeroMap) map[string]*pb.Hero { @@ -20,12 +19,12 @@ func GetHeros(hm HeroMap) map[string]*pb.Hero {
20 return h 19 return h
21 } 20 }
22 21
23 -func NewHero(id int64) *HeroModel { 22 +func NewHero(id string) *HeroModel {
24 h := &pb.Hero{ 23 h := &pb.Hero{
25 Id: id, 24 Id: id,
26 } 25 }
27 m := &HeroModel{ 26 m := &HeroModel{
28 - MgoColl: db.NewMongoColl(strconv.Itoa(int(id)), h), 27 + Schema: db.NewSchema(id, h),
29 Hero: h, 28 Hero: h,
30 } 29 }
31 return m 30 return m
src/models/prop.go
@@ -3,20 +3,19 @@ package models @@ -3,20 +3,19 @@ package models
3 import ( 3 import (
4 "pro2d/protos/pb" 4 "pro2d/protos/pb"
5 "pro2d/src/components/db" 5 "pro2d/src/components/db"
6 - "strconv"  
7 ) 6 )
8 7
9 type PropModels struct { 8 type PropModels struct {
10 - *db.MgoColl 9 + *db.Schema
11 Prop *pb.Prop 10 Prop *pb.Prop
12 } 11 }
13 12
14 -func NewProp(id int64) *PropModels { 13 +func NewProp(id string) *PropModels {
15 data := &pb.Prop{ 14 data := &pb.Prop{
16 Id: id, 15 Id: id,
17 } 16 }
18 m := &PropModels{ 17 m := &PropModels{
19 - MgoColl: db.NewMongoColl(strconv.Itoa(int(id)), data), 18 + Schema: db.NewSchema(id, data),
20 Prop: data, 19 Prop: data,
21 } 20 }
22 21
src/models/role.go
@@ -5,11 +5,10 @@ import ( @@ -5,11 +5,10 @@ import (
5 "pro2d/protos/pb" 5 "pro2d/protos/pb"
6 "pro2d/src/components/db" 6 "pro2d/src/components/db"
7 "pro2d/src/components/logger" 7 "pro2d/src/components/logger"
8 - "strconv"  
9 ) 8 )
10 9
11 type RoleModel struct { 10 type RoleModel struct {
12 - *db.MgoColl 11 + *db.Schema
13 Role *pb.Role 12 Role *pb.Role
14 Heros HeroMap 13 Heros HeroMap
15 Teams *TeamModel 14 Teams *TeamModel
@@ -27,7 +26,7 @@ func RoleExistByUid(uid string) *RoleModel { @@ -27,7 +26,7 @@ func RoleExistByUid(uid string) *RoleModel {
27 26
28 27
29 r := &RoleModel{ 28 r := &RoleModel{
30 - MgoColl: db.NewMongoColl(strconv.Itoa(int(data.Id)), data), 29 + Schema: db.NewSchema(data.Id, data),
31 Role: data, 30 Role: data,
32 Heros: make(HeroMap), 31 Heros: make(HeroMap),
33 Teams: new(TeamModel), 32 Teams: new(TeamModel),
@@ -38,10 +37,10 @@ func RoleExistByUid(uid string) *RoleModel { @@ -38,10 +37,10 @@ func RoleExistByUid(uid string) *RoleModel {
38 return r 37 return r
39 } 38 }
40 39
41 -func NewRole(id int64) *RoleModel { 40 +func NewRole(id string) *RoleModel {
42 data := &pb.Role{Id: id} 41 data := &pb.Role{Id: id}
43 m := &RoleModel{ 42 m := &RoleModel{
44 - MgoColl: db.NewMongoColl(strconv.Itoa(int(id)), data), 43 + Schema: db.NewSchema(id, data),
45 Role: data, 44 Role: data,
46 Heros: make(HeroMap), 45 Heros: make(HeroMap),
47 Teams: new(TeamModel), 46 Teams: new(TeamModel),
@@ -52,9 +51,9 @@ func NewRole(id int64) *RoleModel { @@ -52,9 +51,9 @@ func NewRole(id int64) *RoleModel {
52 } 51 }
53 52
54 func (m *RoleModel) LoadHero() { 53 func (m *RoleModel) LoadHero() {
55 - m.Heros["test"] = NewHero(0) 54 + m.Heros["test"] = NewHero("")
56 m.Heros["test"].Hero = &pb.Hero{ 55 m.Heros["test"].Hero = &pb.Hero{
57 - Id: 1, 56 + Id: "1",
58 RoleId: m.Role.Id, 57 RoleId: m.Role.Id,
59 Type: 1, 58 Type: 1,
60 Level: 1, 59 Level: 1,
@@ -65,17 +64,17 @@ func (m *RoleModel) LoadHero() { @@ -65,17 +64,17 @@ func (m *RoleModel) LoadHero() {
65 } 64 }
66 65
67 func (m *RoleModel) LoadTeams() { 66 func (m *RoleModel) LoadTeams() {
68 - m.Teams = NewTeam(0) 67 + m.Teams = NewTeam("0")
69 m.Teams.Team = &pb.Team{ 68 m.Teams.Team = &pb.Team{
70 - Id: 1, 69 + Id: "1",
71 HeroIds: "1", 70 HeroIds: "1",
72 } 71 }
73 } 72 }
74 73
75 func (m *RoleModel) LoadEquips() { 74 func (m *RoleModel) LoadEquips() {
76 - m.Equip = NewEquip(0) 75 + m.Equip = NewEquip("0")
77 m.Equip.Equip = &pb.Equipment{ 76 m.Equip.Equip = &pb.Equipment{
78 - Id: 0, 77 + Id: "0",
79 RoleId: m.Role.Id, 78 RoleId: m.Role.Id,
80 Type: 0, 79 Type: 0,
81 Equip: false, 80 Equip: false,
@@ -93,7 +92,7 @@ func (m *RoleModel) AddHero(hero *pb.Hero) { @@ -93,7 +92,7 @@ func (m *RoleModel) AddHero(hero *pb.Hero) {
93 h := NewHero(hero.Id) 92 h := NewHero(hero.Id)
94 h.Hero = hero 93 h.Hero = hero
95 h.Create() 94 h.Create()
96 - m.Heros[fmt.Sprintf("%d%d", m.Role.Id, h.Hero.Id)] = h 95 + m.Heros[fmt.Sprintf("%s%s", m.Role.Id, h.Hero.Id)] = h
97 } 96 }
98 97
99 func (m *RoleModel) GetAllHero() map[string]*pb.Hero { 98 func (m *RoleModel) GetAllHero() map[string]*pb.Hero {
src/models/role_test.go
@@ -2,7 +2,7 @@ package models @@ -2,7 +2,7 @@ package models
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
5 - "pro2d/conf" 5 + _ "pro2d/conf"
6 "pro2d/protos/pb" 6 "pro2d/protos/pb"
7 "pro2d/src/components/db" 7 "pro2d/src/components/db"
8 "pro2d/src/components/logger" 8 "pro2d/src/components/logger"
@@ -13,29 +13,29 @@ import ( @@ -13,29 +13,29 @@ import (
13 func TestNewRole(t *testing.T) { 13 func TestNewRole(t *testing.T) {
14 db.MongoDatabase = db.MongoClient.Database("game") 14 db.MongoDatabase = db.MongoClient.Database("game")
15 15
16 - var uid = conf.SnowFlack.NextValStr() 16 + var uid = "141815055745814528"
17 role := RoleExistByUid(uid) 17 role := RoleExistByUid(uid)
18 if role != nil { 18 if role != nil {
19 //uid存在 , 更新角色 19 //uid存在 , 更新角色
20 - role.Role.Device = "222222"  
21 - role.AddHero(&pb.Hero{  
22 - Id: 1,  
23 - RoleId: role.Role.Id,  
24 - Type: 0,  
25 - Level: 0,  
26 - ReinCount: 0,  
27 - ReinPoint: 0,  
28 - Equipments: "",  
29 - })  
30 - role.Save() 20 + //role.AddHero(&pb.Hero{
  21 + // Id: 1,
  22 + // RoleId: role.Role.Id,
  23 + // Type: 0,
  24 + // Level: 0,
  25 + // ReinCount: 0,
  26 + // ReinPoint: 0,
  27 + // Equipments: "",
  28 + //})
  29 + role.UpdateProperty("Device", "999999999")
  30 + //role.Save()
31 }else { 31 }else {
32 //uid不存在,创建角色 32 //uid不存在,创建角色
33 - role = NewRole(1) 33 + role = NewRole("1")
34 role.Role.Uid = uid 34 role.Role.Uid = uid
35 role.Role.Device = "111111" 35 role.Role.Device = "111111"
36 role.Role.Level = 0 36 role.Role.Level = 0
37 - i, err := role.Create()  
38 - fmt.Println(i, err) 37 + err := role.Create()
  38 + fmt.Println(err)
39 } 39 }
40 print(role) 40 print(role)
41 } 41 }
src/models/team.go
@@ -3,20 +3,19 @@ package models @@ -3,20 +3,19 @@ package models
3 import ( 3 import (
4 "pro2d/protos/pb" 4 "pro2d/protos/pb"
5 "pro2d/src/components/db" 5 "pro2d/src/components/db"
6 - "strconv"  
7 ) 6 )
8 7
9 type TeamModel struct { 8 type TeamModel struct {
10 - *db.MgoColl 9 + *db.Schema
11 Team *pb.Team 10 Team *pb.Team
12 } 11 }
13 12
14 -func NewTeam(id int64) *TeamModel { 13 +func NewTeam(id string) *TeamModel {
15 data := &pb.Team{ 14 data := &pb.Team{
16 Id: id, 15 Id: id,
17 } 16 }
18 m := &TeamModel{ 17 m := &TeamModel{
19 - MgoColl: db.NewMongoColl(strconv.Itoa(int(id)), data), 18 + Schema: db.NewSchema(id, data),
20 Team: data, 19 Team: data,
21 } 20 }
22 21
src/plugin/RolePlugin.go
@@ -25,9 +25,9 @@ func CreateRpc(msg *net.MsgPkg) (int32, proto.Message) { @@ -25,9 +25,9 @@ func CreateRpc(msg *net.MsgPkg) (int32, proto.Message) {
25 return 2, nil 25 return 2, nil
26 } 26 }
27 27
28 - roleId := conf.SnowFlack.NextVal() 28 + roleId := conf.SnowFlack.NextValStr()
29 role = models.NewRole(roleId) 29 role = models.NewRole(roleId)
30 - if _, err := role.Create(); err != nil { 30 + if err := role.Create(); err != nil {
31 logger.Error("CreateRpc role create err: %v", err) 31 logger.Error("CreateRpc role create err: %v", err)
32 return 3, nil 32 return 3, nil
33 } 33 }