From 107ff995629bf4a4c554d36304a05bd797fc5460 Mon Sep 17 00:00:00 2001 From: liwei1dao Date: Tue, 21 Jun 2022 13:42:06 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E4=BC=98=E5=8C=96redis=20=E4=BB=A5?= =?UTF-8?q?=E5=8F=8Amodel=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lego/sys/redis/cluster/hash.go | 8 + lego/sys/redis/cluster/key.go | 42 +++-- lego/sys/redis/core.go | 54 +++--- lego/sys/redis/redis.go | 36 ++-- lego/sys/redis/single/key.go | 44 +++-- lego/sys/redis/sys_test.go | 2 +- lego/utils/codec/codec_test.go | 36 ++++ lego/utils/codec/decoder.go | 59 ++++--- lego/utils/codec/encoder.go | 3 +- modules/friend/api_addblack.go | 8 +- modules/friend/api_agree.go | 13 +- modules/friend/api_apply.go | 8 +- modules/friend/api_delblack.go | 6 +- modules/friend/api_refuse.go | 6 +- modules/mail/module.go | 4 +- modules/model_comp.go | 300 ++++++++++++++++++++------------ modules/pack/model_pack_comp.go | 173 ++++++++---------- modules/pack/module.go | 4 +- modules/pack/pack_test.go | 40 +++-- modules/user/api_create.go | 4 +- modules/user/api_login.go | 10 +- pb/pack_db.pb.go | 40 ++--- pb/proto/pack/pack_db.proto | 16 +- 23 files changed, 520 insertions(+), 396 deletions(-) diff --git a/lego/sys/redis/cluster/hash.go b/lego/sys/redis/cluster/hash.go index 4d6eee97a..8cc2cbb20 100644 --- a/lego/sys/redis/cluster/hash.go +++ b/lego/sys/redis/cluster/hash.go @@ -54,6 +54,10 @@ func (this *Redis) HGet(key string, field string, v interface{}) (err error) { this.client.Process(this.getContext(), cmd) var _result string if _result, err = cmd.Result(); err == nil { + if len(_result) == 0 { + err = redis.Nil + return + } err = this.decode.DecoderString(_result, v) } return @@ -68,6 +72,10 @@ func (this *Redis) HGetAll(key string, v interface{}) (err error) { this.client.Process(this.getContext(), cmd) var _result map[string]string if _result, err = cmd.Result(); err == nil { + if len(_result) == 0 { + err = redis.Nil + return + } err = this.decode.DecoderMapString(_result, v) } return diff --git a/lego/sys/redis/cluster/key.go b/lego/sys/redis/cluster/key.go index a464874db..bd2a5e75c 100644 --- a/lego/sys/redis/cluster/key.go +++ b/lego/sys/redis/cluster/key.go @@ -1,7 +1,7 @@ package cluster import ( - "github.com/go-redis/redis/v8" + "time" ) /* Key *******************************************************************************/ @@ -19,64 +19,62 @@ func (this *Redis) ExistsKey(key string) (iskeep bool, err error) { } ///设置key的过期时间 单位以秒级 -func (this *Redis) ExpireKey(key string, expire int) (err error) { - err = this.client.Do(this.getContext(), "EXPIRE", key, expire).Err() +func (this *Redis) Expire(key string, expiration time.Duration) (err error) { + this.client.Expire(this.getContext(), key, expiration) return } ///设置key的过期时间戳 秒级时间戳 -func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { - err = this.client.Do(this.getContext(), "EXPIREAT", key, expire_unix).Err() +func (this *Redis) ExpireAt(key string, tm time.Time) (err error) { + err = this.client.ExpireAt(this.getContext(), key, tm).Err() return } ///设置key的过期时间 单位以毫秒级 -func (this *Redis) Pexpirekey(key string, expire int) (err error) { - err = this.client.Do(this.getContext(), "PEXPIRE", key, expire).Err() +func (this *Redis) PExpire(key string, expiration time.Duration) (err error) { + err = this.client.PExpire(this.getContext(), key, expiration).Err() return } ///设置key的过期时间戳 单位以豪秒级 -func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { - err = this.client.Do(this.getContext(), "PEXPIREAT", key, expire_unix).Err() +func (this *Redis) PExpireAt(key string, tm time.Time) (err error) { + err = this.client.PExpireAt(this.getContext(), key, tm).Err() return } ///移除Key的过期时间 -func (this *Redis) PersistKey(key string) (err error) { - err = this.client.Do(this.getContext(), "PERSIST", key).Err() +func (this *Redis) Persist(key string) (err error) { + err = this.client.Persist(this.getContext(), key).Err() return } ///获取key剩余过期时间 单位毫秒 -func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { - leftexpire, err = this.client.Do(this.getContext(), "PTTL", key).Int64() +func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) { + leftexpire, err = this.client.PTTL(this.getContext(), key).Result() return } ///获取key剩余过期时间 单位秒 -func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { - leftexpire, err = this.client.Do(this.getContext(), "TTL", key).Int64() +func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) { + leftexpire, err = this.client.TTL(this.getContext(), key).Result() return } ///重命名Key -func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { - err = this.client.Do(this.getContext(), "RENAME", oldkey, newkey).Err() +func (this *Redis) Rename(oldkey string, newkey string) (err error) { + err = this.client.Rename(this.getContext(), oldkey, newkey).Err() return } ///重命名key 在新的 key 不存在时修改 key 的名称 -func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { - err = this.client.Do(this.getContext(), "RENAMENX", oldkey, newkey).Err() +func (this *Redis) RenameNX(oldkey string, newkey string) (err error) { + err = this.client.RenameNX(this.getContext(), oldkey, newkey).Err() return } ///判断是否存在key pattern:key* func (this *Redis) Keys(pattern string) (keys []string, err error) { - cmd := redis.NewStringSliceCmd(this.getContext(), "KEYS", string(pattern)) - this.client.Process(this.getContext(), cmd) - keys, err = cmd.Result() + keys, err = this.client.Keys(this.getContext(), pattern).Result() return } diff --git a/lego/sys/redis/core.go b/lego/sys/redis/core.go index ea76412c3..fc7545619 100644 --- a/lego/sys/redis/core.go +++ b/lego/sys/redis/core.go @@ -19,15 +19,15 @@ type ( /*Key*/ Delete(key string) (err error) ExistsKey(key string) (iskeep bool, err error) - ExpireKey(key string, expire int) (err error) - ExpireatKey(key string, expire_unix int64) (err error) - Pexpirekey(key string, expire int) (err error) - PexpireatKey(key string, expire_unix int64) (err error) - PersistKey(key string) (err error) - PttlKey(key string) (leftexpire int64, err error) - TtlKey(key string) (leftexpire int64, err error) - RenameKye(oldkey string, newkey string) (err error) - RenamenxKey(oldkey string, newkey string) (err error) + Expire(key string, expiration time.Duration) (err error) + ExpireAt(key string, tm time.Time) (err error) + PExpire(key string, expiration time.Duration) (err error) + PExpireAt(key string, tm time.Time) (err error) + Persist(key string) (err error) + PTTL(key string) (leftexpire time.Duration, err error) + TTL(key string) (leftexpire time.Duration, err error) + Rename(oldkey string, newkey string) (err error) + RenameNX(oldkey string, newkey string) (err error) Keys(pattern string) (keys []string, err error) Type(key string) (ty string, err error) /*String*/ @@ -158,32 +158,32 @@ func Delete(key string) (err error) { func ExistsKey(key string) (iskeep bool, err error) { return defsys.ExistsKey(key) } -func ExpireKey(key string, expire int) (err error) { - return defsys.ExpireKey(key, expire) +func Expire(key string, expiration time.Duration) (err error) { + return defsys.Expire(key, expiration) } -func ExpireatKey(key string, expire_unix int64) (err error) { - return defsys.ExpireatKey(key, expire_unix) +func ExpireAt(key string, tm time.Time) (err error) { + return defsys.ExpireAt(key, tm) } -func Pexpirekey(key string, expire int) (err error) { - return defsys.Pexpirekey(key, expire) +func PExpire(key string, expiration time.Duration) (err error) { + return defsys.PExpire(key, expiration) } -func PexpireatKey(key string, expire_unix int64) (err error) { - return defsys.PexpireatKey(key, expire_unix) +func PExpireAt(key string, tm time.Time) (err error) { + return defsys.PExpireAt(key, tm) } -func PersistKey(key string) (err error) { - return defsys.PersistKey(key) +func Persist(key string) (err error) { + return defsys.Persist(key) } -func PttlKey(key string) (leftexpire int64, err error) { - return defsys.PttlKey(key) +func PTTL(key string) (leftexpire time.Duration, err error) { + return defsys.PTTL(key) } -func TtlKey(key string) (leftexpire int64, err error) { - return defsys.TtlKey(key) +func TTL(key string) (leftexpire time.Duration, err error) { + return defsys.TTL(key) } -func RenameKye(oldkey string, newkey string) (err error) { - return defsys.RenameKye(oldkey, newkey) +func Rename(oldkey string, newkey string) (err error) { + return defsys.Rename(oldkey, newkey) } -func RenamenxKey(oldkey string, newkey string) (err error) { - return defsys.RenamenxKey(oldkey, newkey) +func RenameNX(oldkey string, newkey string) (err error) { + return defsys.RenameNX(oldkey, newkey) } func Keys(pattern string) (keys []string, err error) { return defsys.Keys(pattern) diff --git a/lego/sys/redis/redis.go b/lego/sys/redis/redis.go index 56f3ad61f..ab119af6b 100644 --- a/lego/sys/redis/redis.go +++ b/lego/sys/redis/redis.go @@ -90,32 +90,32 @@ func (this *Redis) ExistsKey(key string) (iskeep bool, err error) { return this.client.ExistsKey(key) } -func (this *Redis) ExpireKey(key string, expire int) (err error) { - return this.client.ExpireKey(key, expire) +func (this *Redis) Expire(key string, expire time.Duration) (err error) { + return this.client.Expire(key, expire) } -func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { - return this.client.ExpireatKey(key, expire_unix) +func (this *Redis) ExpireAt(key string, tm time.Time) (err error) { + return this.client.ExpireAt(key, tm) } -func (this *Redis) Pexpirekey(key string, expire int) (err error) { - return this.client.Pexpirekey(key, expire) +func (this *Redis) PExpire(key string, expire time.Duration) (err error) { + return this.client.PExpire(key, expire) } -func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { - return this.client.PexpireatKey(key, expire_unix) +func (this *Redis) PExpireAt(key string, tm time.Time) (err error) { + return this.client.PExpireAt(key, tm) } -func (this *Redis) PersistKey(key string) (err error) { - return this.client.PersistKey(key) +func (this *Redis) Persist(key string) (err error) { + return this.client.Persist(key) } -func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { - return this.client.PttlKey(key) +func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) { + return this.client.PTTL(key) } -func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { - return this.client.TtlKey(key) +func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) { + return this.client.TTL(key) } -func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { - return this.client.RenameKye(oldkey, newkey) +func (this *Redis) Rename(oldkey string, newkey string) (err error) { + return this.client.Rename(oldkey, newkey) } -func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { - return this.client.RenamenxKey(oldkey, newkey) +func (this *Redis) RenameNX(oldkey string, newkey string) (err error) { + return this.client.RenameNX(oldkey, newkey) } func (this *Redis) Keys(pattern string) (keys []string, err error) { return this.client.Keys(pattern) diff --git a/lego/sys/redis/single/key.go b/lego/sys/redis/single/key.go index 8d6b46ec5..c246b05c8 100644 --- a/lego/sys/redis/single/key.go +++ b/lego/sys/redis/single/key.go @@ -1,8 +1,6 @@ package single -import ( - "github.com/go-redis/redis/v8" -) +import "time" /* Key *******************************************************************************/ @@ -19,64 +17,62 @@ func (this *Redis) ExistsKey(key string) (iskeep bool, err error) { } ///设置key的过期时间 单位以秒级 -func (this *Redis) ExpireKey(key string, expire int) (err error) { - err = this.client.Do(this.getContext(), "EXPIRE", key, expire).Err() +func (this *Redis) Expire(key string, expiration time.Duration) (err error) { + this.client.Expire(this.getContext(), key, expiration) return } ///设置key的过期时间戳 秒级时间戳 -func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { - err = this.client.Do(this.getContext(), "EXPIREAT", key, expire_unix).Err() +func (this *Redis) ExpireAt(key string, tm time.Time) (err error) { + err = this.client.ExpireAt(this.getContext(), key, tm).Err() return } ///设置key的过期时间 单位以毫秒级 -func (this *Redis) Pexpirekey(key string, expire int) (err error) { - err = this.client.Do(this.getContext(), "PEXPIRE", key, expire).Err() +func (this *Redis) PExpire(key string, expiration time.Duration) (err error) { + err = this.client.PExpire(this.getContext(), key, expiration).Err() return } ///设置key的过期时间戳 单位以豪秒级 -func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { - err = this.client.Do(this.getContext(), "PEXPIREAT", key, expire_unix).Err() +func (this *Redis) PExpireAt(key string, tm time.Time) (err error) { + err = this.client.PExpireAt(this.getContext(), key, tm).Err() return } ///移除Key的过期时间 -func (this *Redis) PersistKey(key string) (err error) { - err = this.client.Do(this.getContext(), "PERSIST", key).Err() +func (this *Redis) Persist(key string) (err error) { + err = this.client.Persist(this.getContext(), key).Err() return } ///获取key剩余过期时间 单位毫秒 -func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { - leftexpire, err = this.client.Do(this.getContext(), "PTTL", key).Int64() +func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) { + leftexpire, err = this.client.PTTL(this.getContext(), key).Result() return } ///获取key剩余过期时间 单位秒 -func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { - leftexpire, err = this.client.Do(this.getContext(), "TTL", key).Int64() +func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) { + leftexpire, err = this.client.TTL(this.getContext(), key).Result() return } ///重命名Key -func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { - err = this.client.Do(this.getContext(), "RENAME", oldkey, newkey).Err() +func (this *Redis) Rename(oldkey string, newkey string) (err error) { + err = this.client.Rename(this.getContext(), oldkey, newkey).Err() return } ///重命名key 在新的 key 不存在时修改 key 的名称 -func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { - err = this.client.Do(this.getContext(), "RENAMENX", oldkey, newkey).Err() +func (this *Redis) RenameNX(oldkey string, newkey string) (err error) { + err = this.client.RenameNX(this.getContext(), oldkey, newkey).Err() return } ///判断是否存在key pattern:key* func (this *Redis) Keys(pattern string) (keys []string, err error) { - cmd := redis.NewStringSliceCmd(this.getContext(), "KEYS", string(pattern)) - this.client.Process(this.getContext(), cmd) - keys, err = cmd.Result() + keys, err = this.client.Keys(this.getContext(), pattern).Result() return } diff --git a/lego/sys/redis/sys_test.go b/lego/sys/redis/sys_test.go index b1619f261..3d690774c 100644 --- a/lego/sys/redis/sys_test.go +++ b/lego/sys/redis/sys_test.go @@ -58,7 +58,7 @@ func Test_Redis_ExpireatKey(t *testing.T) { if err = redis.Set("liwei1dao", 123, -1); err != nil { fmt.Printf("Redis:err:%v \n", err) } - if err = redis.ExpireKey("liwei1dao", 120); err != nil { + if err = redis.Expire("liwei1dao", 120); err != nil { fmt.Printf("Redis:err:%v \n", err) } fmt.Printf("Redis:end \n") diff --git a/lego/utils/codec/codec_test.go b/lego/utils/codec/codec_test.go index 8c91b79cd..c04930b97 100644 --- a/lego/utils/codec/codec_test.go +++ b/lego/utils/codec/codec_test.go @@ -1,6 +1,7 @@ package codec import ( + "encoding/json" "fmt" "testing" ) @@ -27,3 +28,38 @@ func Test_Decoder(t *testing.T) { err := decoder.DecoderMapString(map[string]string{"Fild_1": "liwei1dao"}, data) fmt.Printf("DecoderMap data1:%v err:%v", data, err) } + +func Test_Slice_Decoder(t *testing.T) { + decoder := &Decoder{DefDecoder: json.Unmarshal} + encoder := &Encoder{DefEncoder: json.Marshal} + data := []*TestData{{Fild_1: "1dao", Fild_3: 10, Fild_4: 3.5}, {Fild_1: "2dao", Fild_3: 20, Fild_4: 6.5}} + datastr, err := encoder.EncoderToSliceString(data) + fmt.Printf("EncoderToSliceString datastr:%v err:%v", datastr, err) + if err != nil { + return + } + data1 := make([]*TestData, 0) + err = decoder.DecoderSliceString(datastr, data1) + fmt.Printf("DecoderMap data1:%v err:%v", data1, err) +} + +func Test_Slice_Type(t *testing.T) { + decoder := &Decoder{DefDecoder: json.Unmarshal} + encoder := &Encoder{DefEncoder: json.Marshal} + data := []*TestData{{Fild_1: "1dao", Fild_3: 10, Fild_4: 3.5}, {Fild_1: "2dao", Fild_3: 20, Fild_4: 6.5}} + datastr, err := encoder.EncoderToSliceString(data) + fmt.Printf("EncoderToSliceString datastr:%v err:%v", datastr, err) + if err != nil { + return + } + data1 := make([]*TestData, 0) + err = decoder.DecoderSliceString(datastr, &data1) + fmt.Printf("DecoderMap data1:%v err:%v", data1, err) +} + +func Test_EncoderToMapString(t *testing.T) { + encoder := &Encoder{DefEncoder: json.Marshal} + data := &TestData{Fild_1: "1dao", Fild_3: 10, Fild_4: 3.5} + _map, err := encoder.EncoderToMapString(data) + fmt.Printf("DecoderMap map:%v err:%v", _map, err) +} diff --git a/lego/utils/codec/decoder.go b/lego/utils/codec/decoder.go index a72cac39d..83adb73da 100644 --- a/lego/utils/codec/decoder.go +++ b/lego/utils/codec/decoder.go @@ -326,31 +326,44 @@ func (this *Decoder) DecoderMapString(data map[string]string, v interface{}) err //redis 存储解析 针对 string 转换 func (this *Decoder) DecoderSliceString(data []string, v interface{}) error { - vof := reflect.ValueOf(v) - if !vof.IsValid() { - return fmt.Errorf("Decoder: DecoderMap(nil)") + t := reflect.TypeOf(v) + if t.Kind() == reflect.Ptr { + t = t.Elem() } - if vof.Kind() != reflect.Ptr && vof.Kind() != reflect.Map && vof.Kind() != reflect.Slice { - return fmt.Errorf("Decoder: DecoderMap(non-pointer %T)", v) - } - if vof.Kind() == reflect.Slice { - elemType := vof.Type().Elem() - for _, buf := range data { - if vof.Len() < vof.Cap() { - vof.Set(vof.Slice(0, vof.Len()+1)) - elem := vof.Index(vof.Len() - 1) - if elem.IsNil() { - elem.Set(reflect.New(elemType)) - } - this.DecoderString(buf, elem.Elem().Addr().Interface()) - continue - } - elem := reflect.New(elemType) - vof.Set(reflect.Append(vof, elem)) - this.DecoderString(buf, elem.Elem().Addr().Interface()) - } + + if t.Kind() == reflect.Slice { + t = t.Elem() } else { - return fmt.Errorf("Decoder: DecoderSliceString(invalid type %T)", v) + panic("Input param is not a slice") + } + + sl := reflect.ValueOf(v) + + if t.Kind() == reflect.Ptr { + sl = sl.Elem() + } + + st := sl.Type() + fmt.Printf("Slice Type %s:\n", st) + + sliceType := st.Elem() + if sliceType.Kind() == reflect.Ptr { + sliceType = sliceType.Elem() + } + fmt.Printf("Slice Elem Type %v:\n", sliceType) + for _, buf := range data { + if sl.Len() < sl.Cap() { + sl.Set(sl.Slice(0, sl.Len()+1)) + elem := sl.Index(sl.Len() - 1) + if elem.IsNil() { + elem.Set(reflect.New(sliceType)) + } + this.DecoderString(buf, elem.Elem().Addr().Interface()) + continue + } + elem := reflect.New(sliceType) + sl.Set(reflect.Append(sl, elem)) + this.DecoderString(buf, elem.Elem().Addr().Interface()) } return nil } diff --git a/lego/utils/codec/encoder.go b/lego/utils/codec/encoder.go index 6e78225da..14cbab1ea 100644 --- a/lego/utils/codec/encoder.go +++ b/lego/utils/codec/encoder.go @@ -218,7 +218,7 @@ func (this *Encoder) EncoderToMapString(v interface{}) (data map[string]string, tag := fieldInfo.Tag name := tag.Get("json") if len(name) == 0 { - name = fieldInfo.Name + continue } field := elem.Field(i).Interface() var valuedata string @@ -244,6 +244,7 @@ func (this *Encoder) EncoderToSliceString(v interface{}) (data []string, err err } // vof = vof.Elem() if vof.Kind() == reflect.Slice { + data = make([]string, vof.Len()) for i := 0; i < vof.Len(); i++ { value := vof.Index(i).Interface() var valuedata string diff --git a/modules/friend/api_addblack.go b/modules/friend/api_addblack.go index a468f2b9a..7883d3fa3 100644 --- a/modules/friend/api_addblack.go +++ b/modules/friend/api_addblack.go @@ -15,13 +15,13 @@ func (this *ApiComp) Addblack_Check(session comm.IUserSession, req *pb.Friend_Bl self := &pb.DB_FriendData{UserId: session.GetUserId()} target := &pb.DB_FriendData{UserId: req.FriendId} - err = this.module.model_friend.GetObj(session.GetUserId(), self) + err = this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return } - err = this.module.model_friend.GetObj(req.FriendId, target) + err = this.module.model_friend.Get(req.FriendId, target) if target == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData} return @@ -72,7 +72,9 @@ func (this *ApiComp) Addblack(session comm.IUserSession, chk map[string]interfac self.BlackIds = append(self.BlackIds, req.FriendId) //更新黑名单 - err := this.module.model_friend.SetObj(self.UserId, self) + err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + "blackIds": self.BlackIds, + }) if err != nil { code = pb.ErrorCode_DBError return diff --git a/modules/friend/api_agree.go b/modules/friend/api_agree.go index b98598bdf..6a12927ae 100644 --- a/modules/friend/api_agree.go +++ b/modules/friend/api_agree.go @@ -12,7 +12,7 @@ func (this *ApiComp) Agree_Check(session comm.IUserSession, req *pb.Friend_Agree self := &pb.DB_FriendData{UserId: session.GetUserId()} //获取玩家自己好友数据 - err = this.module.model_friend.GetObj(session.GetUserId(), self) + err = this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return @@ -71,7 +71,7 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{} //双向添加:将自己加入到申请人的好友列表中 target := &pb.DB_FriendData{} - err := this.module.model_friend.GetObj(userId, target) + err := this.module.model_friend.Get(userId, target) if target == nil || err != nil { code = pb.ErrorCode_FriendTargetNoData @@ -82,7 +82,9 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{} } target.FriendIds = append(target.FriendIds, self.UserId) } - err = this.module.model_friend.SetObj(target.UserId, target) + err = this.module.model_friend.Change(target.UserId, map[string]interface{}{ + "friendIds": target.FriendIds, + }) if err != nil { code = pb.ErrorCode_DBError } @@ -93,7 +95,10 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{} } //更新 - err := this.module.model_friend.SetObj(self.UserId, self) + err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + "applyIds": self.ApplyIds, + "friendIds": self.FriendIds, + }) if err != nil { code = pb.ErrorCode_DBError return diff --git a/modules/friend/api_apply.go b/modules/friend/api_apply.go index dd594d528..cb869363e 100644 --- a/modules/friend/api_apply.go +++ b/modules/friend/api_apply.go @@ -14,14 +14,14 @@ func (this *ApiComp) Apply_Check(session comm.IUserSession, req *pb.Friend_Apply target := &pb.DB_FriendData{UserId: req.FriendId} //获取玩家自己好友数据 - err = this.module.model_friend.GetObj(session.GetUserId(), self) + err = this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return } //获取好友数据 - err = this.module.model_friend.GetObj(req.FriendId, target) + err = this.module.model_friend.Get(req.FriendId, target) if target == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData} return @@ -116,7 +116,9 @@ func (this *ApiComp) Apply(session comm.IUserSession, chk map[string]interface{} } target.ApplyIds = append(target.ApplyIds, session.GetUserId()) - err := this.module.model_friend.SetObj(req.FriendId, target) + err := this.module.model_friend.Change(req.FriendId, map[string]interface{}{ + "applyIds": target.ApplyIds, + }) if err != nil { log.Errorf("firend Apply err:%v", err) code = pb.ErrorCode_FriendApplyError diff --git a/modules/friend/api_delblack.go b/modules/friend/api_delblack.go index e7c7b7742..66ff0bc4a 100644 --- a/modules/friend/api_delblack.go +++ b/modules/friend/api_delblack.go @@ -9,7 +9,7 @@ import ( func (this *ApiComp) Delblack_Check(session comm.IUserSession, req *pb.Friend_DelBlack_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) self := &pb.DB_FriendData{UserId: session.GetUserId()} - err := this.module.model_friend.GetObj(session.GetUserId(), self) + err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return @@ -43,7 +43,9 @@ func (this *ApiComp) Delblack(session comm.IUserSession, chk map[string]interfac //从黑名单列表中删除目标 self.BlackIds = utils.DeleteString(self.BlackIds, req.FriendId) //更新黑名单 - err := this.module.model_friend.SetObj(self.UserId, self) + err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + "blackIds": self.BlackIds, + }) if err != nil { code = pb.ErrorCode_DBError return diff --git a/modules/friend/api_refuse.go b/modules/friend/api_refuse.go index d42b00acb..c0a41ee19 100644 --- a/modules/friend/api_refuse.go +++ b/modules/friend/api_refuse.go @@ -12,7 +12,7 @@ func (this *ApiComp) Refuse_Check(session comm.IUserSession, req *pb.Friend_Refu self := &pb.DB_FriendData{UserId: session.GetUserId()} //获取玩家自己好友数据 - err = this.module.model_friend.GetObj(session.GetUserId(), self) + err = this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return @@ -66,7 +66,9 @@ func (this *ApiComp) Refuse(session comm.IUserSession, chk map[string]interface{ } //更新 if optNum > 0 { - err := this.module.model_friend.SetObj(self.UserId, self) + err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + "applyIds": self.ApplyIds, + }) if err != nil { code = pb.ErrorCode_DBError return diff --git a/modules/mail/module.go b/modules/mail/module.go index 226a87553..8b6d2a2bc 100644 --- a/modules/mail/module.go +++ b/modules/mail/module.go @@ -56,8 +56,8 @@ func (this *Mail) CreateNewMail(uId string) { log.Error("create mail failed") } // 通知玩家 - var _cache *pb.Cache_UserData - err = this.db_comp.Model_Comp.GetObj(uId, _cache) + var _cache = &pb.Cache_UserData{} + err = this.db_comp.Model_Comp.Get(uId, _cache) if err == nil { return } diff --git a/modules/model_comp.go b/modules/model_comp.go index 0ce2aab81..5341854cb 100644 --- a/modules/model_comp.go +++ b/modules/model_comp.go @@ -1,6 +1,7 @@ package modules import ( + "context" "fmt" "go_dreamfactory/comm" "go_dreamfactory/lego/core" @@ -16,7 +17,6 @@ import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" - "google.golang.org/protobuf/proto" ) /* @@ -49,6 +49,9 @@ func (this *Model_Comp) Start() (err error) { func (this *Model_Comp) ukey(uid string) string { return fmt.Sprintf("%s:%s", this.TableName, uid) } +func (this *Model_Comp) ukeylist(uid string, id string) string { + return fmt.Sprintf("%s:%s-%s", this.TableName, uid, id) +} func (this *Model_Comp) InsertModelLogs(table string, uID string, target interface{}) (err error) { @@ -85,7 +88,6 @@ func (this *Model_Comp) DeleteModelLogs(table string, uID string, where interfac return err } - func (this *Model_Comp) UpdateModelLogs(table string, uID string, where bson.M, target interface{}) (err error) { data := &comm.Autogenerated{ @@ -105,134 +107,216 @@ func (this *Model_Comp) UpdateModelLogs(table string, uID string, where bson.M, return err } -//设置缓存JSON格式数据 -//data 值允许protobuf格式的对象 -// attrs 操作可选项目 eg.传入WithDisabledMgoLog() 表示关闭日志,否则开启;WithND() 传入表示插入操作,不传表示更新,前提不能传入传入WithDisabledMgoLog() -func (this *Model_Comp) SetObj(uid string, data proto.Message, attrs ...*cache.OperationAttr) error { - expr := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(time.Second * 0).(time.Duration) - err := this.Redis.Set(this.ukey(uid), data, expr) - if err != nil { - log.Errorf("set err:%v", err) - return err +//添加新的数据 +func (this *Model_Comp) Add(uid string, data interface{}, attrs ...*cache.OperationAttr) (err error) { + if err = this.Redis.HMSet(this.ukey(uid), data); err != nil { + return } - - return this.logOpt(uid, data, attrs...) + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil { + this.Redis.Expire(this.ukey(uid), ret.(time.Duration)) + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_MGOLOG).Unwrap_Or(nil); ret == nil { + err = this.InsertModelLogs(this.TableName, uid, data) + } + return } -//缓存多个字段的数据 data参数 允许map或protobuf -//eg.map[string]*TestData{"li_1": {Name: "liwei2dao", Agr: 56}, "li_2": {Name: "liwei3dao", Agr: 78}} -//or &TestData{Name: "liwei1dao", Agr: 12, Sub: &TestAny{SubName: "test", Age: 20}} -// attrs 操作可选项目 eg.传入WithDisabledMgoLog() 表示关闭日志,否则开启;WithND() 传入表示插入操作,不传表示更新,前提不能传入传入WithDisabledMgoLog() -//如果更新数据,uid作为where条件之一,如果检索结果不能确定唯一,此时data 必需是map[string]interface{}类型,必需包含_id 字段 -func (this *Model_Comp) SetHM(uid string, data interface{}, attrs ...*cache.OperationAttr) error { - err := this.Redis.HMSet(this.ukey(uid), data) - if err != nil { - log.Errorf("SetHM err: %v", err) - return err +//添加新的数据 +func (this *Model_Comp) AddList(uid string, id string, data interface{}, attrs ...*cache.OperationAttr) (err error) { + key := this.ukeylist(uid, id) + if err = this.Redis.HMSet(key, data); err != nil { + return } - - return this.logOpt(uid, data, attrs...) + if err = this.Redis.HSet(this.ukey(uid), id, key); err != nil { + return + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil { + this.Redis.Expire(this.ukey(uid), ret.(time.Duration)) + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_MGOLOG).Unwrap_Or(nil); ret == nil { + err = this.InsertModelLogs(this.TableName, uid, data) + } + return } -//缓存一个字段的数据 -//如果更新数据,uid作为where条件之一,如果检索结果不能确定唯一,此时data 必需是map[string]interface{}类型,必需包含_id 字段 -func (this *Model_Comp) SetH(uid string, field string, data interface{}, attrs ...*cache.OperationAttr) error { - err := this.Redis.HSet(this.ukey(uid), field, data) - if err != nil { - log.Errorf("SetH err %v", err) - return err +//修改数据多个字段 uid 作为主键 +func (this *Model_Comp) Change(uid string, data map[string]interface{}, attrs ...*cache.OperationAttr) (err error) { + if err = this.Redis.HMSet(this.ukey(uid), data); err != nil { + return } - return this.logOpt(uid, data, attrs...) + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil { + this.Redis.Expire(this.ukey(uid), ret.(time.Duration)) + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_MGOLOG).Unwrap_Or(nil); ret == nil { + err = this.UpdateModelLogs(this.TableName, uid, bson.M{"uid": uid}, data) + } + return nil } -//获取缓存JSON数据 -func (this *Model_Comp) GetObj(uid string, v proto.Message) error { - err := this.Redis.Get(this.ukey(uid), v) - if err != nil { - if err == redis.RedisNil { - //query from mgo - err = this.DB.FindOne(core.SqlTable(this.TableName), bson.M{"_id": uid}).Decode(v) - if err != nil { - //no record - if err == mongo.ErrNoDocuments { - _, err = this.DB.InsertOne(core.SqlTable(this.TableName), v) - if err != nil { - log.Errorf("insert err: %v", err) - return err - } - //set cache - return this.SetObj(uid, v, cache.WithND()) +//修改数据多个字段 uid 作为主键 +func (this *Model_Comp) ChangeList(uid string, _id string, data map[string]interface{}, attrs ...*cache.OperationAttr) (err error) { + if err = this.Redis.HMSet(this.ukeylist(uid, _id), data); err != nil { + return + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil { + this.Redis.Expire(this.ukey(uid), ret.(time.Duration)) + } + if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_MGOLOG).Unwrap_Or(nil); ret == nil { + err = this.UpdateModelLogs(this.TableName, uid, bson.M{"_id": _id, "uid": uid}, data) + } + return nil +} + +//读取全部数据 +func (this *Model_Comp) Get(uid string, data interface{}) (err error) { + if err = this.Redis.HGetAll(this.ukey(uid), data); err != nil { + return + } + if err == redis.RedisNil { + //query from mgo + if err = this.DB.FindOne(core.SqlTable(this.TableName), bson.M{"uid": uid}).Decode(data); err != nil { + return + } + err = this.Redis.HMSet(this.ukey(uid), data) + } + return +} + +//获取列表数据 注意 data 必须啊转 切片的指针 *[]type +func (this *Model_Comp) GetList(uid string, data interface{}) (err error) { + var keys map[string]string = make(map[string]string) + var c *mongo.Cursor + t := reflect.TypeOf(data) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + + if t.Kind() == reflect.Slice { + t = t.Elem() + } else { + panic("Input param is not a slice") + } + + sl := reflect.ValueOf(data) + + if t.Kind() == reflect.Ptr { + sl = sl.Elem() + } + + st := sl.Type() + fmt.Printf("Slice Type %s:\n", st) + + sliceType := st.Elem() + if sliceType.Kind() == reflect.Ptr { + sliceType = sliceType.Elem() + } + fmt.Printf("Slice Elem Type %v:\n", sliceType) + err = this.Redis.HGetAll(this.ukey(uid), keys) + if err == nil { + for _, v := range keys { + if sl.Len() < sl.Cap() { + sl.Set(sl.Slice(0, sl.Len()+1)) + elem := sl.Index(sl.Len() - 1) + if elem.IsNil() { + elem.Set(reflect.New(sliceType)) } + if err = this.Redis.HGetAll(v, elem.Elem().Addr().Interface()); err != nil { + return + } + continue + } + elem := reflect.New(sliceType) + sl.Set(reflect.Append(sl, elem)) + if err = this.Redis.HGetAll(v, elem.Elem().Addr().Interface()); err != nil { + return } - } else { - log.Errorf("get cache err: %v", err) } } + if err == redis.RedisNil { + //query from mgo + if c, err = this.DB.Find(core.SqlTable(this.TableName), bson.M{"uid": uid}); err != nil { + return err + } else { + var temp map[string]interface{} = make(map[string]interface{}) + var keys map[string]string = make(map[string]string) + for c.Next(context.Background()) { + _id := c.Current.Lookup("_id").StringValue() + if sl.Len() < sl.Cap() { + sl.Set(sl.Slice(0, sl.Len()+1)) + elem := sl.Index(sl.Len() - 1) + if elem.IsNil() { + elem.Set(reflect.New(sliceType)) + } + if err = c.Decode(elem.Elem().Addr().Interface()); err != nil { + return + } + temp[_id] = elem.Elem().Addr().Interface() + continue + } + elem := reflect.New(sliceType) + sl.Set(reflect.Append(sl, elem)) + if err = c.Decode(elem.Elem().Addr().Interface()); err != nil { + return + } + temp[_id] = elem.Elem().Addr().Interface() + } + for k, v := range temp { + key := this.ukeylist(uid, k) + if err = this.Redis.HMSet(key, v); err != nil { + return + } + keys[k] = key + } + if err = this.Redis.HMSet(this.ukey(uid), keys); err != nil { + return + } + } + } + return err } -//获取对象所有字段数据 -//data类型map或protobuf -func (this *Model_Comp) GetHM(uid string, data interface{}) error { - ok, err := this.Redis.ExistsKey(this.ukey(uid)) +//读取单个数据中 多个字段数据 +func (this *Model_Comp) GetFields(uid string, data interface{}, fields ...string) (err error) { + this.Redis.HMGet(this.ukey(uid), data, fields...) + return +} + +//读取List列表中单个数据中 多个字段数据 +func (this *Model_Comp) GetListFields(uid string, id string, data interface{}, fields ...string) (err error) { + this.Redis.HMGet(this.ukeylist(uid, id), data, fields...) + return +} + +//读取列表数据中单个数据 +func (this *Model_Comp) GetListObj(uid string, id string, data interface{}) (err error) { + err = this.Redis.HGetAll(this.ukeylist(uid, id), data) + return +} + +//删除用户数据 +func (this *Model_Comp) Del(uid string) (err error) { + err = this.Redis.Delete(this.ukey(uid)) if err != nil { - log.Errorf("key no exist %v", this.ukey(uid)) return err } - if ok { - return this.Redis.HGetAll(this.ukey(uid), data) - } else { - filter := bson.M{"uid": uid} - c, err2 := this.DB.Find(core.SqlTable(this.TableName), filter) - if err2 != nil { - log.Errorf("GetHM-find err:%v", err) - return err + err = this.DeleteModelLogs(this.TableName, uid, bson.M{"uid": uid}) + return nil +} + +//删除多条数据 +func (this *Model_Comp) DelListlds(uid string, ids ...string) (err error) { + listkey := this.ukey(uid) + for _, v := range ids { + key := this.ukeylist(uid, v) + if err = this.Redis.Delete(key); err != nil { + return } - err2 = c.Decode(data) - if err2 != nil { - log.Errorf("GetHM-find decode err:%v", err) - return err - } - //update cache without mgolog - return this.SetHM(this.ukey(uid), data, cache.WithDisabledMgoLog()) } - -} - -//获取字段数据 缓存存储的数据为hashmap时 -func (this *Model_Comp) GetH(uid string, field string, v interface{}) error { - return this.Redis.HGet(this.ukey(uid), field, v) -} - -//删除一条数据 -func (this *Model_Comp) DelH(uid string) error { - err := this.Redis.HDel(this.ukey(uid)) - if err != nil { - log.Errorf("del err:%v", err) - return err + if err = this.Redis.HDel(listkey, ids...); err == nil { + err = this.DeleteModelLogs(this.TableName, uid, bson.M{"_id": bson.M{"$in": ids}}) } - - return this.DeleteModelLogs(this.TableName, uid, bson.M{"uid": uid}) -} - -//删除缓存字段 -func (this *Model_Comp) DelHF(uid string, fields ...string) error { - err := this.Redis.HDel(this.ukey(uid), fields...) - if err != nil { - log.Errorf("DelHF err: %v", err) - return err - } - - //get new data after delete - data := make(map[string]interface{}) - err = this.Redis.HGetAll(this.ukey(uid), data) - if err != nil { - log.Errorf("DelHF-HGetAll err: %v", err) - return err - } - - //cache with mgolog - return this.SetHM(this.ukey(uid), data) + return } //日志操作可选项 diff --git a/modules/pack/model_pack_comp.go b/modules/pack/model_pack_comp.go index 5542c1fb0..78b0e14f2 100644 --- a/modules/pack/model_pack_comp.go +++ b/modules/pack/model_pack_comp.go @@ -31,97 +31,45 @@ func (this *Model_Pack_Comp) Init(service core.IService, module core.IModule, co ///查询用户背包数据 func (this *Model_Pack_Comp) Pack_QueryUserPack(uId string) (itmes []*pb.DB_UserItemData, err error) { - var ( - data map[string]*pb.DB_UserItemData = make(map[string]*pb.DB_UserItemData) - ) - if err = this.GetHM(uId, data); err == nil { - itmes = make([]*pb.DB_UserItemData, len(data)) - n := 0 - for _, v := range data { - itmes[n] = v - n++ - } - } - // var ( - // lists []interface{} - // temp map[string]interface{} - // ) - // if lists, err = this.Redis.HGetAll(fmt.Sprintf(Redis_PackCache, uId), reflect.TypeOf(pb.DB_UserItemData{})); err == nil { - // itmes = make([]*pb.DB_UserItemData, 0, len(lists)) - // for i, v := range lists { - // itmes[i] = v.(*pb.DB_UserItemData) - // } - // return - // } else if err == redis.RedisNil { - // if itmes, err = this.module.db_comp.Pack_QueryUserPack(uId); err == nil { - // temp = make(map[string]interface{}) - // for _, v := range itmes { - // temp[v.GridId] = v - // } - // this.Redis.HMSet(fmt.Sprintf(Redis_PackCache, uId), temp) - // } else if err == mgo.MongodbNil { - // err = nil - // } - // } + itmes = make([]*pb.DB_UserItemData, 0) + err = this.GetList(uId, &itmes) return } ///查询用户指定格子的物品数据 func (this *Model_Pack_Comp) Pack_QueryUserPackByGridId(uId string, grid string) (itme *pb.DB_UserItemData, err error) { itme = &pb.DB_UserItemData{} - err = this.GetH(uId, grid, itme) + err = this.GetListObj(uId, grid, itme) + return +} - // var ( - // itmes []*pb.DB_UserItemData - // temp map[string]interface{} - // ) - // itme = &pb.DB_UserItemData{} - // if err = this.Redis.HGet(fmt.Sprintf(Redis_PackCache, uId), grid, itme); err == nil { - // return - // } else if err == redis.RedisNil { - // if itmes, err = this.module.db_comp.Pack_QueryUserPack(uId); err == nil { - // temp = make(map[string]interface{}) - // for _, v := range itmes { - // temp[v.GridId] = v - // } - // this.Redis.HMSet(fmt.Sprintf(Redis_PackCache, uId), temp) - // for _, v := range itmes { - // if v.GridId == grid { - // itme = v - // return - // } - // } - // err = fmt.Errorf("no found uid:%s grid:%s", uId, grid) - // } else if err == mgo.MongodbNil { - // err = nil - // } - // } +//更新用户的背包信息 +func (this *Model_Pack_Comp) Pack_AddUserPack(uId string, itmes ...*pb.DB_UserItemData) (err error) { + for _, v := range itmes { + this.AddList(uId, v.GridId, v) + } + return +} + +//更新用户的背包信息 +func (this *Model_Pack_Comp) Pack_DelUserPack(uId string, ids ...string) (err error) { + err = this.DelListlds(uId, ids...) return } //更新用户的背包信息 func (this *Model_Pack_Comp) Pack_UpdateUserPack(uId string, itmes ...*pb.DB_UserItemData) (err error) { - var data map[string]*pb.DB_UserItemData = make(map[string]*pb.DB_UserItemData) for _, v := range itmes { - data[v.GridId] = v + this.ChangeList(uId, v.GridId, map[string]interface{}{ + "amount": v.Amount, + }) } - err = this.SetHM(uId, data) - // temp := make(map[string]interface{}) - // for _, v := range itmes { - // temp[v.GridId] = v - // } - // if err = this.Redis.HMSet(fmt.Sprintf(Redis_PackCache, uId), temp); err != nil { - // this.module.db_comp.Pack_UpdateGridToUserPack(uId, itmes...) - // } - return } //更新用户的背包信息 func (this *Model_Pack_Comp) Pack_DeleteUserPack(uId string, gridIds ...string) (err error) { - if err = this.Redis.HDel(fmt.Sprintf(Redis_PackCache, uId), gridIds...); err != nil { - err = this.module.db_comp.Pack_DeleteGridToUserPack(uId, gridIds...) - } + err = this.DelListlds(uId, gridIds...) return } @@ -146,7 +94,9 @@ func (this *Model_Pack_Comp) Pack_QueryUserPackItemAmount(uId string, itemid int func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, addnum int32) (err error) { var ( itmes []*pb.DB_UserItemData - modifys []*pb.DB_UserItemData + add []*pb.DB_UserItemData + del []string + update []*pb.DB_UserItemData leftnum int64 ) if addnum == 0 { @@ -155,7 +105,7 @@ func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, ad if itmes, err = this.Pack_QueryUserPack(uId); err != nil { return } - modifys, leftnum = this.pack_addItemToUserPack(itmes, itemId, addnum) + add, update, del, leftnum = this.pack_addItemToUserPack(itmes, itemId, addnum) if leftnum < 0 { err = ItemNotEnoughError return @@ -163,24 +113,39 @@ func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, ad err = PackGridNumUpper return } - this.Pack_UpdateUserPack(uId, modifys...) + if len(add) > 0 { + if err = this.Pack_AddUserPack(uId, add...); err != nil { + return + } + } + if len(del) > 0 { + if err = this.Pack_AddUserPack(uId, add...); err != nil { + return + } + } + if len(update) > 0 { + if err = this.Pack_UpdateUserPack(uId, update...); err != nil { + return + } + } + return } ///添加或则减少多个物品到用户背包 func (this *Model_Pack_Comp) Pack_AddItemsToUserPack(uId string, items map[int32]int32) (err error) { var ( - itmes []*pb.DB_UserItemData - modifys []*pb.DB_UserItemData - tempmodifys []*pb.DB_UserItemData - leftnum int64 - iskeep bool + itmes []*pb.DB_UserItemData + add []*pb.DB_UserItemData + del []string + update []*pb.DB_UserItemData + leftnum int64 ) if itmes, err = this.Pack_QueryUserPack(uId); err != nil { return } for k, v := range items { - tempmodifys, leftnum = this.pack_addItemToUserPack(itmes, k, v) + add, update, del, leftnum = this.pack_addItemToUserPack(itmes, k, v) if leftnum < 0 { err = ItemNotEnoughError return @@ -188,20 +153,22 @@ func (this *Model_Pack_Comp) Pack_AddItemsToUserPack(uId string, items map[int32 err = PackGridNumUpper return } - for _, v1 := range tempmodifys { - iskeep = false - for _, v2 := range modifys { - if v1.GridId == v2.GridId { - iskeep = true - } + if len(add) > 0 { + if err = this.Pack_AddUserPack(uId, add...); err != nil { + return } - if !iskeep { - modifys = append(modifys, v1) + } + if len(del) > 0 { + if err = this.Pack_AddUserPack(uId, add...); err != nil { + return + } + } + if len(update) > 0 { + if err = this.Pack_UpdateUserPack(uId, update...); err != nil { + return } } } - - this.Pack_UpdateUserPack(uId, modifys...) return } @@ -241,7 +208,7 @@ func (this *Model_Pack_Comp) Pack_AddItemToUserPackByGrid(uId string, gridid str } ///添加移除物品到用户背包 -func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, itemId int32, addnum int32) (modifys []*pb.DB_UserItemData, leftnum int64) { +func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, itemId int32, addnum int32) (add, update []*pb.DB_UserItemData, del []string, leftnum int64) { var ( num int64 isNew bool @@ -251,7 +218,9 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, } isNew = true leftnum = int64(addnum) - modifys = make([]*pb.DB_UserItemData, 0) + add = make([]*pb.DB_UserItemData, 0) + del = make([]string, 0) + update = make([]*pb.DB_UserItemData, 0) for _, v := range items { if !v.IsEmpty && v.ItemId == itemId { isNew = false @@ -260,30 +229,30 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, leftnum += int64(v.Amount) v.Amount = 0 v.IsEmpty = true - modifys = append(modifys, v) + del = append(del, v.GridId) } else if num > 0 && num < int64(v.Amount) { leftnum = 0 v.Amount = uint32(num) - modifys = append(modifys, v) + update = append(update, v) break } else if num > 0 && num > int64(v.Amount) { if num <= GridCapMaxNum { leftnum = 0 v.Amount = uint32(num) - modifys = append(modifys, v) + update = append(update, v) break } else { if v.Amount < GridCapMaxNum { leftnum = int64(num - GridCapMaxNum) v.Amount = uint32(GridCapMaxNum) - modifys = append(modifys, v) + update = append(update, v) } } } else if num == 0 { leftnum = 0 v.Amount = 0 v.IsEmpty = true - modifys = append(modifys, v) + del = append(del, v.GridId) } } } @@ -298,14 +267,14 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, v.ItemId = itemId v.Amount = uint32(leftnum) leftnum = 0 - modifys = append(modifys, v) + update = append(update, v) break } else { leftnum -= GridCapMaxNum v.IsEmpty = false v.ItemId = itemId v.Amount = uint32(GridCapMaxNum) - modifys = append(modifys, v) + update = append(update, v) } } } @@ -320,7 +289,7 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, IsNewItem: isNew, } items = append(items, grid) - modifys = append(modifys, grid) + add = append(add, grid) leftnum = 0 break } else { @@ -333,7 +302,7 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData, IsNewItem: isNew, } items = append(items, grid) - modifys = append(modifys, grid) + add = append(add, grid) index++ } if index > GridMaxNUm { //格子已达上限 diff --git a/modules/pack/module.go b/modules/pack/module.go index 98e199d1a..691579c49 100644 --- a/modules/pack/module.go +++ b/modules/pack/module.go @@ -22,8 +22,8 @@ type Pack struct { modules.ModuleBase api_comp *Api_Comp model_pack_comp *Model_Pack_Comp - db_comp *DB_Comp - configure_comp *Configure_Comp + // db_comp *DB_Comp + configure_comp *Configure_Comp } //模块名称 diff --git a/modules/pack/pack_test.go b/modules/pack/pack_test.go index 688ef21c4..8d8817c48 100644 --- a/modules/pack/pack_test.go +++ b/modules/pack/pack_test.go @@ -16,10 +16,7 @@ import ( "testing" "time" - "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" ) func newService(ops ...rpcx.Option) core.IService { @@ -78,9 +75,13 @@ func TestMain(m *testing.M) { func Test_Log(t *testing.T) { // data, _ := ptypes.MarshalAny(&pb.Pack_Getlist_Req{}) // s_gateComp.ReceiveMsg(context.Background(), &pb.AgentMessage{Method: "pack.getlist", Message: data}, &pb.RPCMessageReply{}) + // itmes := make([]*pb.DB_UserItemData, 0) + // err := module.model_pack_comp.GetList("0_62a9afd994fe03b7aaee6773", &itmes) + // log.Debugf("item:%v err:%v", itmes, err) + // module.model_pack_comp.Get() +} - // items, err := module.db_comp.Pack_QueryUserPack("liwei1dao") - // log.Debugf("item:%v err:%v", items, err) +func Test_Pack_UpdateGridToUserPack(t *testing.T) { uid := "0_62a9afd994fe03b7aaee6773" Pack_UpdateGridToUserPack( uid, @@ -135,19 +136,24 @@ func Test_Log(t *testing.T) { //更新背包格子数据 func Pack_UpdateGridToUserPack(uId string, grids ...*pb.DB_UserItemData) (err error) { - models := make([]mongo.WriteModel, len(grids)) + // models := make([]mongo.WriteModel, len(grids)) + // for i, v := range grids { + // models[i] = mongo.NewUpdateOneModel().SetFilter(bson.M{"_id": v.GridId}).SetUpdate( + // bson.M{"$set": bson.M{ + // "uid": v.UId, + // "isempty": v.IsEmpty, + // "itemid": v.ItemId, + // "amount": v.Amount, + // "ctime": v.CTime, + // "etime": v.ETime, + // "isnewitem": v.IsNewItem, + // }}).SetUpsert(true) + // } + // module.model_pack_comp.DB.BulkWrite(DB_PackTable, models, options.BulkWrite().SetOrdered(false)) + data := make([]interface{}, len(grids)) for i, v := range grids { - models[i] = mongo.NewUpdateOneModel().SetFilter(bson.M{"_id": v.GridId}).SetUpdate( - bson.M{"$set": bson.M{ - "uid": v.UId, - "isempty": v.IsEmpty, - "itemid": v.ItemId, - "amount": v.Amount, - "ctime": v.CTime, - "etime": v.ETime, - "isnewitem": v.IsNewItem, - }}).SetUpsert(true) + data[i] = v } - module.model_pack_comp.DB.BulkWrite(DB_PackTable, models, options.BulkWrite().SetOrdered(false)) + module.model_pack_comp.DB.InsertMany(DB_PackTable, data) return } diff --git a/modules/user/api_create.go b/modules/user/api_create.go index 43ac9b643..37d012d10 100644 --- a/modules/user/api_create.go +++ b/modules/user/api_create.go @@ -25,13 +25,13 @@ func (this *Api_Comp) Create(session comm.IUserSession, result map[string]interf // update := map[string]interface{}{ // "name": req.NickName, // } - err := this.module.modelUser.GetObj(session.GetUserId(), self) + err := this.module.modelUser.Get(session.GetUserId(), self) if err != nil { code = pb.ErrorCode_DBError return } self.Name = req.NickName - err = this.module.modelUser.SetObj(session.GetUserId(), self) + err = this.module.modelUser.Get(session.GetUserId(), self) if err != nil { code = pb.ErrorCode_DBError return diff --git a/modules/user/api_login.go b/modules/user/api_login.go index b92a42215..2bac4ba22 100644 --- a/modules/user/api_login.go +++ b/modules/user/api_login.go @@ -69,10 +69,10 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa user.Createip = session.GetIP() //缓存user session - err = this.module.modelSession.SetObj(user.Uid, &pb.Cache_UserData{ - Uid: user.Uid, - SessionId: session.GetSessionId(), - GatewayServiceId: session.GetGatewayServiceId(), + err = this.module.modelSession.Change(user.Uid, map[string]interface{}{ + "uId": user.Uid, + "sessionId": session.GetSessionId(), + "gatewayServiceId": session.GetGatewayServiceId(), }, cache.WithExpire(time.Hour*12), cache.WithDisabledMgoLog()) @@ -82,7 +82,7 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa } //缓存user - err = this.module.modelUser.SetObj(user.Uid, user) + err = this.module.modelUser.Add(user.Uid, user, cache.WithDisabledMgoLog()) if err != nil { code = pb.ErrorCode_DBError return diff --git a/pb/pack_db.pb.go b/pb/pack_db.pb.go index b353fea0f..40abbf07f 100644 --- a/pb/pack_db.pb.go +++ b/pb/pack_db.pb.go @@ -26,14 +26,14 @@ type DB_UserItemData struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - GridId string `protobuf:"bytes,1,opt,name=GridId,proto3" json:"GridId"` //背包格子Id - UId string `protobuf:"bytes,2,opt,name=UId,proto3" json:"UId"` //用户id - IsEmpty bool `protobuf:"varint,3,opt,name=IsEmpty,proto3" json:"IsEmpty"` //是否是空格子 - ItemId int32 `protobuf:"varint,4,opt,name=ItemId,proto3" json:"ItemId"` //存放物品的Id - Amount uint32 `protobuf:"varint,5,opt,name=Amount,proto3" json:"Amount"` //存放物品的数量 - CTime int64 `protobuf:"varint,6,opt,name=CTime,proto3" json:"CTime"` //物品获取时间 - ETime int64 `protobuf:"varint,7,opt,name=ETime,proto3" json:"ETime"` //物品过期时间 - IsNewItem bool `protobuf:"varint,8,opt,name=IsNewItem,proto3" json:"IsNewItem"` //是否是新的 + GridId string `protobuf:"bytes,1,opt,name=gridId,proto3" json:"gridId" bson:"_id"` // 背包格子Id + UId string `protobuf:"bytes,2,opt,name=uId,proto3" json:"uId" bson:"uId"` // 用户id + IsEmpty bool `protobuf:"varint,3,opt,name=isEmpty,proto3" json:"isEmpty" bson:"isEmpty"` // 是否是空格子 + ItemId int32 `protobuf:"varint,4,opt,name=itemId,proto3" json:"itemId" bson:"itemId"` // 存放物品的Id + Amount uint32 `protobuf:"varint,5,opt,name=amount,proto3" json:"amount" bson:"amount"` // 存放物品的数量 + CTime int64 `protobuf:"varint,6,opt,name=cTime,proto3" json:"cTime" bson:"cTime"` // 物品获取时间 + ETime int64 `protobuf:"varint,7,opt,name=eTime,proto3" json:"eTime" bson:"eTime"` // 物品过期时间 + IsNewItem bool `protobuf:"varint,8,opt,name=isNewItem,proto3" json:"isNewItem" bson:"isNewItem"` // 是否是新的 } func (x *DB_UserItemData) Reset() { @@ -129,18 +129,18 @@ var File_pack_pack_db_proto protoreflect.FileDescriptor var file_pack_pack_db_proto_rawDesc = []byte{ 0x0a, 0x12, 0x70, 0x61, 0x63, 0x6b, 0x2f, 0x70, 0x61, 0x63, 0x6b, 0x5f, 0x64, 0x62, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcf, 0x01, 0x0a, 0x0f, 0x44, 0x42, 0x5f, 0x55, 0x73, 0x65, 0x72, - 0x49, 0x74, 0x65, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x12, 0x16, 0x0a, 0x06, 0x47, 0x72, 0x69, 0x64, - 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x47, 0x72, 0x69, 0x64, 0x49, 0x64, - 0x12, 0x10, 0x0a, 0x03, 0x55, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x55, - 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x49, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x07, 0x49, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x16, 0x0a, 0x06, - 0x49, 0x74, 0x65, 0x6d, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x49, 0x74, - 0x65, 0x6d, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, 0x05, - 0x43, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x43, 0x54, 0x69, - 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x45, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x05, 0x45, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x49, 0x73, 0x4e, 0x65, - 0x77, 0x49, 0x74, 0x65, 0x6d, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x49, 0x73, 0x4e, + 0x49, 0x74, 0x65, 0x6d, 0x44, 0x61, 0x74, 0x61, 0x12, 0x16, 0x0a, 0x06, 0x67, 0x72, 0x69, 0x64, + 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x67, 0x72, 0x69, 0x64, 0x49, 0x64, + 0x12, 0x10, 0x0a, 0x03, 0x75, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, + 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x69, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x16, 0x0a, 0x06, + 0x69, 0x74, 0x65, 0x6d, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x69, 0x74, + 0x65, 0x6d, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, + 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, 0x05, + 0x63, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x63, 0x54, 0x69, + 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x05, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x69, 0x73, 0x4e, 0x65, + 0x77, 0x49, 0x74, 0x65, 0x6d, 0x18, 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x69, 0x73, 0x4e, 0x65, 0x77, 0x49, 0x74, 0x65, 0x6d, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x3b, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/pb/proto/pack/pack_db.proto b/pb/proto/pack/pack_db.proto index 2afbf07a6..3c1816722 100644 --- a/pb/proto/pack/pack_db.proto +++ b/pb/proto/pack/pack_db.proto @@ -4,12 +4,12 @@ option go_package = ".;pb"; //背包格子 message DB_UserItemData { - string GridId = 1; //背包格子Id - string UId = 2; //用户id - bool IsEmpty = 3; //是否是空格子 - int32 ItemId = 4; //存放物品的Id - uint32 Amount = 5; //存放物品的数量 - int64 CTime = 6; //物品获取时间 - int64 ETime = 7; //物品过期时间 - bool IsNewItem = 8; //是否是新的 + string gridId = 1; //@go_tags(`bson:"_id"`) 背包格子Id + string uId = 2; //@go_tags(`bson:"uId"`) 用户id + bool isEmpty = 3; //@go_tags(`bson:"isEmpty"`) 是否是空格子 + int32 itemId = 4; //@go_tags(`bson:"itemId"`) 存放物品的Id + uint32 amount = 5; //@go_tags(`bson:"amount"`) 存放物品的数量 + int64 cTime = 6; //@go_tags(`bson:"cTime"`) 物品获取时间 + int64 eTime = 7; //@go_tags(`bson:"eTime"`) 物品过期时间 + bool isNewItem = 8; //@go_tags(`bson:"isNewItem"`) 是否是新的 } From f13f5da1c505d4efa3e13680a6d176b77a113856 Mon Sep 17 00:00:00 2001 From: liwei1dao Date: Tue, 21 Jun 2022 13:50:56 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E4=B8=8A=E4=BC=A0pb=20tag=E6=A0=87?= =?UTF-8?q?=E7=AD=BE=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/friend/api_applylist.go | 2 +- modules/friend/api_blacklist.go | 2 +- modules/friend/api_list.go | 2 +- modules/pack/pack_test.go | 7 +++---- pb/pack_db.pb.go | 2 +- pb/proto/pack/pack_db.proto | 2 +- 6 files changed, 8 insertions(+), 9 deletions(-) diff --git a/modules/friend/api_applylist.go b/modules/friend/api_applylist.go index bbeb4c5d7..215b261c1 100644 --- a/modules/friend/api_applylist.go +++ b/modules/friend/api_applylist.go @@ -8,7 +8,7 @@ import ( func (this *ApiComp) ApplyList_Check(session comm.IUserSession, req *pb.Friend_ApplyList_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) self := &pb.DB_FriendData{UserId: session.GetUserId()} - err := this.module.model_friend.GetObj(session.GetUserId(), self) + err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return diff --git a/modules/friend/api_blacklist.go b/modules/friend/api_blacklist.go index 1715d7bbf..24a560f50 100644 --- a/modules/friend/api_blacklist.go +++ b/modules/friend/api_blacklist.go @@ -8,7 +8,7 @@ import ( func (this *ApiComp) Blacklist_Check(session comm.IUserSession, req *pb.Friend_BlackList_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) self := &pb.DB_FriendData{UserId: session.GetUserId()} - err := this.module.model_friend.GetObj(session.GetUserId(), self) + err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return diff --git a/modules/friend/api_list.go b/modules/friend/api_list.go index 7bd6d5055..639c3f36e 100644 --- a/modules/friend/api_list.go +++ b/modules/friend/api_list.go @@ -8,7 +8,7 @@ import ( func (this *ApiComp) List_Check(session comm.IUserSession, req *pb.Friend_List_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) self := &pb.DB_FriendData{UserId: session.GetUserId()} - err := this.module.model_friend.GetObj(session.GetUserId(), self) + err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} return diff --git a/modules/pack/pack_test.go b/modules/pack/pack_test.go index 8d8817c48..97db5a364 100644 --- a/modules/pack/pack_test.go +++ b/modules/pack/pack_test.go @@ -75,10 +75,9 @@ func TestMain(m *testing.M) { func Test_Log(t *testing.T) { // data, _ := ptypes.MarshalAny(&pb.Pack_Getlist_Req{}) // s_gateComp.ReceiveMsg(context.Background(), &pb.AgentMessage{Method: "pack.getlist", Message: data}, &pb.RPCMessageReply{}) - // itmes := make([]*pb.DB_UserItemData, 0) - // err := module.model_pack_comp.GetList("0_62a9afd994fe03b7aaee6773", &itmes) - // log.Debugf("item:%v err:%v", itmes, err) - // module.model_pack_comp.Get() + itmes := make([]*pb.DB_UserItemData, 0) + err := module.model_pack_comp.GetList("0_62a9afd994fe03b7aaee6773", &itmes) + log.Debugf("item:%v err:%v", itmes, err) } func Test_Pack_UpdateGridToUserPack(t *testing.T) { diff --git a/pb/pack_db.pb.go b/pb/pack_db.pb.go index 40abbf07f..f014b399f 100644 --- a/pb/pack_db.pb.go +++ b/pb/pack_db.pb.go @@ -27,7 +27,7 @@ type DB_UserItemData struct { unknownFields protoimpl.UnknownFields GridId string `protobuf:"bytes,1,opt,name=gridId,proto3" json:"gridId" bson:"_id"` // 背包格子Id - UId string `protobuf:"bytes,2,opt,name=uId,proto3" json:"uId" bson:"uId"` // 用户id + UId string `protobuf:"bytes,2,opt,name=uId,proto3" json:"uId" bson:"uid"` // 用户id IsEmpty bool `protobuf:"varint,3,opt,name=isEmpty,proto3" json:"isEmpty" bson:"isEmpty"` // 是否是空格子 ItemId int32 `protobuf:"varint,4,opt,name=itemId,proto3" json:"itemId" bson:"itemId"` // 存放物品的Id Amount uint32 `protobuf:"varint,5,opt,name=amount,proto3" json:"amount" bson:"amount"` // 存放物品的数量 diff --git a/pb/proto/pack/pack_db.proto b/pb/proto/pack/pack_db.proto index 3c1816722..b68505424 100644 --- a/pb/proto/pack/pack_db.proto +++ b/pb/proto/pack/pack_db.proto @@ -5,7 +5,7 @@ option go_package = ".;pb"; //背包格子 message DB_UserItemData { string gridId = 1; //@go_tags(`bson:"_id"`) 背包格子Id - string uId = 2; //@go_tags(`bson:"uId"`) 用户id + string uId = 2; //@go_tags(`bson:"uid"`) 用户id bool isEmpty = 3; //@go_tags(`bson:"isEmpty"`) 是否是空格子 int32 itemId = 4; //@go_tags(`bson:"itemId"`) 存放物品的Id uint32 amount = 5; //@go_tags(`bson:"amount"`) 存放物品的数量 From 14710e9893243f856132f861574369487254ee47 Mon Sep 17 00:00:00 2001 From: liwei1dao Date: Tue, 21 Jun 2022 13:55:52 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E5=90=8C=E6=AD=A5dev?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/friend/api_addblack.go | 2 +- modules/friend/api_agree.go | 4 ++-- modules/friend/api_applylist.go | 2 +- modules/friend/api_blacklist.go | 2 +- modules/friend/api_delblack.go | 4 ++-- modules/friend/api_list.go | 2 +- modules/friend/api_refuse.go | 2 +- modules/pack/pack_test.go | 7 ------- modules/user/api_login.go | 6 +++--- 9 files changed, 12 insertions(+), 19 deletions(-) diff --git a/modules/friend/api_addblack.go b/modules/friend/api_addblack.go index 326c9b948..7d8b3a4d3 100644 --- a/modules/friend/api_addblack.go +++ b/modules/friend/api_addblack.go @@ -78,7 +78,7 @@ func (this *ApiComp) Addblack(session comm.IUserSession, chk map[string]interfac self.BlackIds = append(self.BlackIds, req.FriendId) //更新黑名单 - err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + err := this.module.model_friend.Change(self.UId, map[string]interface{}{ "blackIds": self.BlackIds, }) if err != nil { diff --git a/modules/friend/api_agree.go b/modules/friend/api_agree.go index 1b812dc1d..ea0f92335 100644 --- a/modules/friend/api_agree.go +++ b/modules/friend/api_agree.go @@ -82,7 +82,7 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{} } target.FriendIds = append(target.FriendIds, self.UId) } - err = this.module.model_friend.Change(target.UserId, map[string]interface{}{ + err = this.module.model_friend.Change(target.UId, map[string]interface{}{ "friendIds": target.FriendIds, }) if err != nil { @@ -95,7 +95,7 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{} } //更新 - err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + err := this.module.model_friend.Change(self.UId, map[string]interface{}{ "applyIds": self.ApplyIds, "friendIds": self.FriendIds, }) diff --git a/modules/friend/api_applylist.go b/modules/friend/api_applylist.go index 215b261c1..a470345ee 100644 --- a/modules/friend/api_applylist.go +++ b/modules/friend/api_applylist.go @@ -7,7 +7,7 @@ import ( func (this *ApiComp) ApplyList_Check(session comm.IUserSession, req *pb.Friend_ApplyList_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) - self := &pb.DB_FriendData{UserId: session.GetUserId()} + self := &pb.DB_FriendData{UId: session.GetUserId()} err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} diff --git a/modules/friend/api_blacklist.go b/modules/friend/api_blacklist.go index 24a560f50..61047e218 100644 --- a/modules/friend/api_blacklist.go +++ b/modules/friend/api_blacklist.go @@ -7,7 +7,7 @@ import ( func (this *ApiComp) Blacklist_Check(session comm.IUserSession, req *pb.Friend_BlackList_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) - self := &pb.DB_FriendData{UserId: session.GetUserId()} + self := &pb.DB_FriendData{UId: session.GetUserId()} err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} diff --git a/modules/friend/api_delblack.go b/modules/friend/api_delblack.go index 4e341ce17..91adb395d 100644 --- a/modules/friend/api_delblack.go +++ b/modules/friend/api_delblack.go @@ -8,7 +8,7 @@ import ( func (this *ApiComp) Delblack_Check(session comm.IUserSession, req *pb.Friend_DelBlack_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) - self := &pb.DB_FriendData{UserId: session.GetUserId()} + self := &pb.DB_FriendData{UId: session.GetUserId()} err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} @@ -43,7 +43,7 @@ func (this *ApiComp) Delblack(session comm.IUserSession, chk map[string]interfac //从黑名单列表中删除目标 self.BlackIds = utils.DeleteString(self.BlackIds, req.FriendId) //更新黑名单 - err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + err := this.module.model_friend.Change(self.UId, map[string]interface{}{ "blackIds": self.BlackIds, }) if err != nil { diff --git a/modules/friend/api_list.go b/modules/friend/api_list.go index 639c3f36e..0ad9499a3 100644 --- a/modules/friend/api_list.go +++ b/modules/friend/api_list.go @@ -7,7 +7,7 @@ import ( func (this *ApiComp) List_Check(session comm.IUserSession, req *pb.Friend_List_Req) (chk map[string]interface{}, code comm.ErrorCode) { chk = make(map[string]interface{}) - self := &pb.DB_FriendData{UserId: session.GetUserId()} + self := &pb.DB_FriendData{UId: session.GetUserId()} err := this.module.model_friend.Get(session.GetUserId(), self) if self == nil || err != nil { code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} diff --git a/modules/friend/api_refuse.go b/modules/friend/api_refuse.go index 03b0eec12..56ee1c593 100644 --- a/modules/friend/api_refuse.go +++ b/modules/friend/api_refuse.go @@ -66,7 +66,7 @@ func (this *ApiComp) Refuse(session comm.IUserSession, chk map[string]interface{ } //更新 if optNum > 0 { - err := this.module.model_friend.Change(self.UserId, map[string]interface{}{ + err := this.module.model_friend.Change(self.UId, map[string]interface{}{ "applyIds": self.ApplyIds, }) if err != nil { diff --git a/modules/pack/pack_test.go b/modules/pack/pack_test.go index 95a38164e..39b09a2b0 100644 --- a/modules/pack/pack_test.go +++ b/modules/pack/pack_test.go @@ -156,10 +156,3 @@ func Pack_UpdateGridToUserPack(uId string, grids ...*pb.DB_UserItemData) (err er module.model_pack_comp.DB.InsertMany(DB_PackTable, data) return } - -func TestGetHM(t *testing.T) { - d := make(map[string]interface{}) - d["amount"] = 10 - d["itemid"] = 1004 - module.cache_comp.SetHM("pack:0_62a9afd994fe03b7aaee6773", d) -} diff --git a/modules/user/api_login.go b/modules/user/api_login.go index 70f754cc3..b3fe4f54f 100644 --- a/modules/user/api_login.go +++ b/modules/user/api_login.go @@ -69,8 +69,8 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa user.Createip = session.GetIP() //缓存user session - err = this.module.modelSession.Change(user.Uid, map[string]interface{}{ - "uId": user.Uid, + err = this.module.modelSession.Change(user.UId, map[string]interface{}{ + "uid": user.UId, "sessionId": session.GetSessionId(), "gatewayServiceId": session.GetGatewayServiceId(), }, @@ -82,7 +82,7 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa } //缓存user - err = this.module.modelUser.Add(user.Uid, user, cache.WithDisabledMgoLog()) + err = this.module.modelUser.Add(user.UId, user, cache.WithDisabledMgoLog()) if err != nil { code = pb.ErrorCode_DBError return