Merge branch 'dev' of http://git.legu.cc/liwei_3d/go_dreamfactory into meixiongfeng

This commit is contained in:
meixiongfeng 2022-06-21 14:00:37 +08:00
commit aa426a1328
26 changed files with 522 additions and 406 deletions

View File

@ -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

View File

@ -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
}

View File

@ -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)

View File

@ -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)

View File

@ -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
}

View File

@ -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")

View File

@ -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)
}

View File

@ -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 t.Kind() == reflect.Slice {
t = t.Elem()
} else {
panic("Input param is not a slice")
}
if vof.Kind() == reflect.Slice {
elemType := vof.Type().Elem()
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 vof.Len() < vof.Cap() {
vof.Set(vof.Slice(0, vof.Len()+1))
elem := vof.Index(vof.Len() - 1)
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(elemType))
elem.Set(reflect.New(sliceType))
}
this.DecoderString(buf, elem.Elem().Addr().Interface())
continue
}
elem := reflect.New(elemType)
vof.Set(reflect.Append(vof, elem))
elem := reflect.New(sliceType)
sl.Set(reflect.Append(sl, elem))
this.DecoderString(buf, elem.Elem().Addr().Interface())
}
} else {
return fmt.Errorf("Decoder: DecoderSliceString(invalid type %T)", v)
}
return nil
}

View File

@ -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

View File

@ -15,13 +15,13 @@ func (this *ApiComp) Addblack_Check(session comm.IUserSession, req *pb.Friend_Bl
self := &pb.DB_FriendData{UId: session.GetUserId()}
target := &pb.DB_FriendData{UId: 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
@ -78,7 +78,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.UId, self)
err := this.module.model_friend.Change(self.UId, map[string]interface{}{
"blackIds": self.BlackIds,
})
if err != nil {
code = pb.ErrorCode_DBError
return

View File

@ -12,7 +12,7 @@ func (this *ApiComp) Agree_Check(session comm.IUserSession, req *pb.Friend_Agree
self := &pb.DB_FriendData{UId: 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.UId)
}
err = this.module.model_friend.SetObj(target.UId, target)
err = this.module.model_friend.Change(target.UId, 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.UId, self)
err := this.module.model_friend.Change(self.UId, map[string]interface{}{
"applyIds": self.ApplyIds,
"friendIds": self.FriendIds,
})
if err != nil {
code = pb.ErrorCode_DBError
return

View File

@ -14,14 +14,14 @@ func (this *ApiComp) Apply_Check(session comm.IUserSession, req *pb.Friend_Apply
target := &pb.DB_FriendData{UId: 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

View File

@ -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{UId: 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

View File

@ -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{UId: 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

View File

@ -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{UId: 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.UId, self)
err := this.module.model_friend.Change(self.UId, map[string]interface{}{
"blackIds": self.BlackIds,
})
if err != nil {
code = pb.ErrorCode_DBError
return

View File

@ -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{UId: 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

View File

@ -12,7 +12,7 @@ func (this *ApiComp) Refuse_Check(session comm.IUserSession, req *pb.Friend_Refu
self := &pb.DB_FriendData{UId: 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.UId, self)
err := this.module.model_friend.Change(self.UId, map[string]interface{}{
"applyIds": self.ApplyIds,
})
if err != nil {
code = pb.ErrorCode_DBError
return

View File

@ -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
}

View File

@ -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 {
//修改数据多个字段 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
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
if err = this.DB.FindOne(core.SqlTable(this.TableName), bson.M{"uid": uid}).Decode(data); err != nil {
return
}
//set cache
return this.SetObj(uid, v, cache.WithND())
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 {
log.Errorf("get cache err: %v", err)
panic("Input param is not a slice")
}
}
return err
}
//获取对象所有字段数据
//data类型map或protobuf
func (this *Model_Comp) GetHM(uid string, data interface{}) error {
ok, err := this.Redis.ExistsKey(this.ukey(uid))
if err != nil {
log.Errorf("key no exist %v", this.ukey(uid))
return err
sl := reflect.ValueOf(data)
if t.Kind() == reflect.Ptr {
sl = sl.Elem()
}
if ok {
return this.Redis.HGetAll(this.ukey(uid), data)
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
}
}
}
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 {
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
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
}
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())
}
return err
}
//获取字段数据 缓存存储的数据为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) GetFields(uid string, data interface{}, fields ...string) (err error) {
this.Redis.HMGet(this.ukey(uid), data, fields...)
return
}
//删除一条数据
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
}
return this.DeleteModelLogs(this.TableName, uid, bson.M{"uid": uid})
//读取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) DelHF(uid string, fields ...string) error {
err := this.Redis.HDel(this.ukey(uid), fields...)
//读取列表数据中单个数据
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("DelHF err: %v", err)
return err
}
err = this.DeleteModelLogs(this.TableName, uid, bson.M{"uid": uid})
return nil
}
//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
//删除多条数据
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
}
//cache with mgolog
return this.SetHM(this.ukey(uid), data)
}
if err = this.Redis.HDel(listkey, ids...); err == nil {
err = this.DeleteModelLogs(this.TableName, uid, bson.M{"_id": bson.M{"$in": ids}})
}
return
}
//日志操作可选项

View File

@ -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,7 +113,22 @@ 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
}
@ -171,16 +136,16 @@ func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, ad
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
add []*pb.DB_UserItemData
del []string
update []*pb.DB_UserItemData
leftnum int64
iskeep bool
)
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 { //格子已达上限

View File

@ -22,7 +22,7 @@ type Pack struct {
modules.ModuleBase
api_comp *Api_Comp
model_pack_comp *Model_Pack_Comp
db_comp *DB_Comp
// db_comp *DB_Comp
configure_comp *Configure_Comp
}

View File

@ -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,12 @@ 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)
}
// 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,26 +135,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
}
func TestGetHM(t *testing.T) {
d := make(map[string]interface{})
d["amount"] = 10
d["itemid"] = 1004
module.cache_comp.SetHM("pack:0_62a9afd994fe03b7aaee6773", d)
}

View File

@ -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

View File

@ -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

View File

@ -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,
}

View File

@ -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"`)
}