优化redis 以及model接口

This commit is contained in:
liwei1dao 2022-06-21 13:42:06 +08:00
parent 5b914746e5
commit 107ff99562
23 changed files with 520 additions and 396 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) this.client.Process(this.getContext(), cmd)
var _result string var _result string
if _result, err = cmd.Result(); err == nil { if _result, err = cmd.Result(); err == nil {
if len(_result) == 0 {
err = redis.Nil
return
}
err = this.decode.DecoderString(_result, v) err = this.decode.DecoderString(_result, v)
} }
return return
@ -68,6 +72,10 @@ func (this *Redis) HGetAll(key string, v interface{}) (err error) {
this.client.Process(this.getContext(), cmd) this.client.Process(this.getContext(), cmd)
var _result map[string]string var _result map[string]string
if _result, err = cmd.Result(); err == nil { if _result, err = cmd.Result(); err == nil {
if len(_result) == 0 {
err = redis.Nil
return
}
err = this.decode.DecoderMapString(_result, v) err = this.decode.DecoderMapString(_result, v)
} }
return return

View File

@ -1,7 +1,7 @@
package cluster package cluster
import ( import (
"github.com/go-redis/redis/v8" "time"
) )
/* Key *******************************************************************************/ /* Key *******************************************************************************/
@ -19,64 +19,62 @@ func (this *Redis) ExistsKey(key string) (iskeep bool, err error) {
} }
///设置key的过期时间 单位以秒级 ///设置key的过期时间 单位以秒级
func (this *Redis) ExpireKey(key string, expire int) (err error) { func (this *Redis) Expire(key string, expiration time.Duration) (err error) {
err = this.client.Do(this.getContext(), "EXPIRE", key, expire).Err() this.client.Expire(this.getContext(), key, expiration)
return return
} }
///设置key的过期时间戳 秒级时间戳 ///设置key的过期时间戳 秒级时间戳
func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) ExpireAt(key string, tm time.Time) (err error) {
err = this.client.Do(this.getContext(), "EXPIREAT", key, expire_unix).Err() err = this.client.ExpireAt(this.getContext(), key, tm).Err()
return return
} }
///设置key的过期时间 单位以毫秒级 ///设置key的过期时间 单位以毫秒级
func (this *Redis) Pexpirekey(key string, expire int) (err error) { func (this *Redis) PExpire(key string, expiration time.Duration) (err error) {
err = this.client.Do(this.getContext(), "PEXPIRE", key, expire).Err() err = this.client.PExpire(this.getContext(), key, expiration).Err()
return return
} }
///设置key的过期时间戳 单位以豪秒级 ///设置key的过期时间戳 单位以豪秒级
func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) PExpireAt(key string, tm time.Time) (err error) {
err = this.client.Do(this.getContext(), "PEXPIREAT", key, expire_unix).Err() err = this.client.PExpireAt(this.getContext(), key, tm).Err()
return return
} }
///移除Key的过期时间 ///移除Key的过期时间
func (this *Redis) PersistKey(key string) (err error) { func (this *Redis) Persist(key string) (err error) {
err = this.client.Do(this.getContext(), "PERSIST", key).Err() err = this.client.Persist(this.getContext(), key).Err()
return return
} }
///获取key剩余过期时间 单位毫秒 ///获取key剩余过期时间 单位毫秒
func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) {
leftexpire, err = this.client.Do(this.getContext(), "PTTL", key).Int64() leftexpire, err = this.client.PTTL(this.getContext(), key).Result()
return return
} }
///获取key剩余过期时间 单位秒 ///获取key剩余过期时间 单位秒
func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) {
leftexpire, err = this.client.Do(this.getContext(), "TTL", key).Int64() leftexpire, err = this.client.TTL(this.getContext(), key).Result()
return return
} }
///重命名Key ///重命名Key
func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { func (this *Redis) Rename(oldkey string, newkey string) (err error) {
err = this.client.Do(this.getContext(), "RENAME", oldkey, newkey).Err() err = this.client.Rename(this.getContext(), oldkey, newkey).Err()
return return
} }
///重命名key 在新的 key 不存在时修改 key 的名称 ///重命名key 在新的 key 不存在时修改 key 的名称
func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { func (this *Redis) RenameNX(oldkey string, newkey string) (err error) {
err = this.client.Do(this.getContext(), "RENAMENX", oldkey, newkey).Err() err = this.client.RenameNX(this.getContext(), oldkey, newkey).Err()
return return
} }
///判断是否存在key pattern:key* ///判断是否存在key pattern:key*
func (this *Redis) Keys(pattern string) (keys []string, err error) { func (this *Redis) Keys(pattern string) (keys []string, err error) {
cmd := redis.NewStringSliceCmd(this.getContext(), "KEYS", string(pattern)) keys, err = this.client.Keys(this.getContext(), pattern).Result()
this.client.Process(this.getContext(), cmd)
keys, err = cmd.Result()
return return
} }

View File

@ -19,15 +19,15 @@ type (
/*Key*/ /*Key*/
Delete(key string) (err error) Delete(key string) (err error)
ExistsKey(key string) (iskeep bool, err error) ExistsKey(key string) (iskeep bool, err error)
ExpireKey(key string, expire int) (err error) Expire(key string, expiration time.Duration) (err error)
ExpireatKey(key string, expire_unix int64) (err error) ExpireAt(key string, tm time.Time) (err error)
Pexpirekey(key string, expire int) (err error) PExpire(key string, expiration time.Duration) (err error)
PexpireatKey(key string, expire_unix int64) (err error) PExpireAt(key string, tm time.Time) (err error)
PersistKey(key string) (err error) Persist(key string) (err error)
PttlKey(key string) (leftexpire int64, err error) PTTL(key string) (leftexpire time.Duration, err error)
TtlKey(key string) (leftexpire int64, err error) TTL(key string) (leftexpire time.Duration, err error)
RenameKye(oldkey string, newkey string) (err error) Rename(oldkey string, newkey string) (err error)
RenamenxKey(oldkey string, newkey string) (err error) RenameNX(oldkey string, newkey string) (err error)
Keys(pattern string) (keys []string, err error) Keys(pattern string) (keys []string, err error)
Type(key string) (ty string, err error) Type(key string) (ty string, err error)
/*String*/ /*String*/
@ -158,32 +158,32 @@ func Delete(key string) (err error) {
func ExistsKey(key string) (iskeep bool, err error) { func ExistsKey(key string) (iskeep bool, err error) {
return defsys.ExistsKey(key) return defsys.ExistsKey(key)
} }
func ExpireKey(key string, expire int) (err error) { func Expire(key string, expiration time.Duration) (err error) {
return defsys.ExpireKey(key, expire) return defsys.Expire(key, expiration)
} }
func ExpireatKey(key string, expire_unix int64) (err error) { func ExpireAt(key string, tm time.Time) (err error) {
return defsys.ExpireatKey(key, expire_unix) return defsys.ExpireAt(key, tm)
} }
func Pexpirekey(key string, expire int) (err error) { func PExpire(key string, expiration time.Duration) (err error) {
return defsys.Pexpirekey(key, expire) return defsys.PExpire(key, expiration)
} }
func PexpireatKey(key string, expire_unix int64) (err error) { func PExpireAt(key string, tm time.Time) (err error) {
return defsys.PexpireatKey(key, expire_unix) return defsys.PExpireAt(key, tm)
} }
func PersistKey(key string) (err error) { func Persist(key string) (err error) {
return defsys.PersistKey(key) return defsys.Persist(key)
} }
func PttlKey(key string) (leftexpire int64, err error) { func PTTL(key string) (leftexpire time.Duration, err error) {
return defsys.PttlKey(key) return defsys.PTTL(key)
} }
func TtlKey(key string) (leftexpire int64, err error) { func TTL(key string) (leftexpire time.Duration, err error) {
return defsys.TtlKey(key) return defsys.TTL(key)
} }
func RenameKye(oldkey string, newkey string) (err error) { func Rename(oldkey string, newkey string) (err error) {
return defsys.RenameKye(oldkey, newkey) return defsys.Rename(oldkey, newkey)
} }
func RenamenxKey(oldkey string, newkey string) (err error) { func RenameNX(oldkey string, newkey string) (err error) {
return defsys.RenamenxKey(oldkey, newkey) return defsys.RenameNX(oldkey, newkey)
} }
func Keys(pattern string) (keys []string, err error) { func Keys(pattern string) (keys []string, err error) {
return defsys.Keys(pattern) 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) return this.client.ExistsKey(key)
} }
func (this *Redis) ExpireKey(key string, expire int) (err error) { func (this *Redis) Expire(key string, expire time.Duration) (err error) {
return this.client.ExpireKey(key, expire) return this.client.Expire(key, expire)
} }
func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) ExpireAt(key string, tm time.Time) (err error) {
return this.client.ExpireatKey(key, expire_unix) return this.client.ExpireAt(key, tm)
} }
func (this *Redis) Pexpirekey(key string, expire int) (err error) { func (this *Redis) PExpire(key string, expire time.Duration) (err error) {
return this.client.Pexpirekey(key, expire) return this.client.PExpire(key, expire)
} }
func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) PExpireAt(key string, tm time.Time) (err error) {
return this.client.PexpireatKey(key, expire_unix) return this.client.PExpireAt(key, tm)
} }
func (this *Redis) PersistKey(key string) (err error) { func (this *Redis) Persist(key string) (err error) {
return this.client.PersistKey(key) return this.client.Persist(key)
} }
func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) {
return this.client.PttlKey(key) return this.client.PTTL(key)
} }
func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) {
return this.client.TtlKey(key) return this.client.TTL(key)
} }
func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { func (this *Redis) Rename(oldkey string, newkey string) (err error) {
return this.client.RenameKye(oldkey, newkey) return this.client.Rename(oldkey, newkey)
} }
func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { func (this *Redis) RenameNX(oldkey string, newkey string) (err error) {
return this.client.RenamenxKey(oldkey, newkey) return this.client.RenameNX(oldkey, newkey)
} }
func (this *Redis) Keys(pattern string) (keys []string, err error) { func (this *Redis) Keys(pattern string) (keys []string, err error) {
return this.client.Keys(pattern) return this.client.Keys(pattern)

View File

@ -1,8 +1,6 @@
package single package single
import ( import "time"
"github.com/go-redis/redis/v8"
)
/* Key *******************************************************************************/ /* Key *******************************************************************************/
@ -19,64 +17,62 @@ func (this *Redis) ExistsKey(key string) (iskeep bool, err error) {
} }
///设置key的过期时间 单位以秒级 ///设置key的过期时间 单位以秒级
func (this *Redis) ExpireKey(key string, expire int) (err error) { func (this *Redis) Expire(key string, expiration time.Duration) (err error) {
err = this.client.Do(this.getContext(), "EXPIRE", key, expire).Err() this.client.Expire(this.getContext(), key, expiration)
return return
} }
///设置key的过期时间戳 秒级时间戳 ///设置key的过期时间戳 秒级时间戳
func (this *Redis) ExpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) ExpireAt(key string, tm time.Time) (err error) {
err = this.client.Do(this.getContext(), "EXPIREAT", key, expire_unix).Err() err = this.client.ExpireAt(this.getContext(), key, tm).Err()
return return
} }
///设置key的过期时间 单位以毫秒级 ///设置key的过期时间 单位以毫秒级
func (this *Redis) Pexpirekey(key string, expire int) (err error) { func (this *Redis) PExpire(key string, expiration time.Duration) (err error) {
err = this.client.Do(this.getContext(), "PEXPIRE", key, expire).Err() err = this.client.PExpire(this.getContext(), key, expiration).Err()
return return
} }
///设置key的过期时间戳 单位以豪秒级 ///设置key的过期时间戳 单位以豪秒级
func (this *Redis) PexpireatKey(key string, expire_unix int64) (err error) { func (this *Redis) PExpireAt(key string, tm time.Time) (err error) {
err = this.client.Do(this.getContext(), "PEXPIREAT", key, expire_unix).Err() err = this.client.PExpireAt(this.getContext(), key, tm).Err()
return return
} }
///移除Key的过期时间 ///移除Key的过期时间
func (this *Redis) PersistKey(key string) (err error) { func (this *Redis) Persist(key string) (err error) {
err = this.client.Do(this.getContext(), "PERSIST", key).Err() err = this.client.Persist(this.getContext(), key).Err()
return return
} }
///获取key剩余过期时间 单位毫秒 ///获取key剩余过期时间 单位毫秒
func (this *Redis) PttlKey(key string) (leftexpire int64, err error) { func (this *Redis) PTTL(key string) (leftexpire time.Duration, err error) {
leftexpire, err = this.client.Do(this.getContext(), "PTTL", key).Int64() leftexpire, err = this.client.PTTL(this.getContext(), key).Result()
return return
} }
///获取key剩余过期时间 单位秒 ///获取key剩余过期时间 单位秒
func (this *Redis) TtlKey(key string) (leftexpire int64, err error) { func (this *Redis) TTL(key string) (leftexpire time.Duration, err error) {
leftexpire, err = this.client.Do(this.getContext(), "TTL", key).Int64() leftexpire, err = this.client.TTL(this.getContext(), key).Result()
return return
} }
///重命名Key ///重命名Key
func (this *Redis) RenameKye(oldkey string, newkey string) (err error) { func (this *Redis) Rename(oldkey string, newkey string) (err error) {
err = this.client.Do(this.getContext(), "RENAME", oldkey, newkey).Err() err = this.client.Rename(this.getContext(), oldkey, newkey).Err()
return return
} }
///重命名key 在新的 key 不存在时修改 key 的名称 ///重命名key 在新的 key 不存在时修改 key 的名称
func (this *Redis) RenamenxKey(oldkey string, newkey string) (err error) { func (this *Redis) RenameNX(oldkey string, newkey string) (err error) {
err = this.client.Do(this.getContext(), "RENAMENX", oldkey, newkey).Err() err = this.client.RenameNX(this.getContext(), oldkey, newkey).Err()
return return
} }
///判断是否存在key pattern:key* ///判断是否存在key pattern:key*
func (this *Redis) Keys(pattern string) (keys []string, err error) { func (this *Redis) Keys(pattern string) (keys []string, err error) {
cmd := redis.NewStringSliceCmd(this.getContext(), "KEYS", string(pattern)) keys, err = this.client.Keys(this.getContext(), pattern).Result()
this.client.Process(this.getContext(), cmd)
keys, err = cmd.Result()
return return
} }

View File

@ -58,7 +58,7 @@ func Test_Redis_ExpireatKey(t *testing.T) {
if err = redis.Set("liwei1dao", 123, -1); err != nil { if err = redis.Set("liwei1dao", 123, -1); err != nil {
fmt.Printf("Redis:err:%v \n", err) 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:err:%v \n", err)
} }
fmt.Printf("Redis:end \n") fmt.Printf("Redis:end \n")

View File

@ -1,6 +1,7 @@
package codec package codec
import ( import (
"encoding/json"
"fmt" "fmt"
"testing" "testing"
) )
@ -27,3 +28,38 @@ func Test_Decoder(t *testing.T) {
err := decoder.DecoderMapString(map[string]string{"Fild_1": "liwei1dao"}, data) err := decoder.DecoderMapString(map[string]string{"Fild_1": "liwei1dao"}, data)
fmt.Printf("DecoderMap data1:%v err:%v", data, err) 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 转换 //redis 存储解析 针对 string 转换
func (this *Decoder) DecoderSliceString(data []string, v interface{}) error { func (this *Decoder) DecoderSliceString(data []string, v interface{}) error {
vof := reflect.ValueOf(v) t := reflect.TypeOf(v)
if !vof.IsValid() { if t.Kind() == reflect.Ptr {
return fmt.Errorf("Decoder: DecoderMap(nil)") 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()
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())
}
} else { } 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 return nil
} }

View File

@ -218,7 +218,7 @@ func (this *Encoder) EncoderToMapString(v interface{}) (data map[string]string,
tag := fieldInfo.Tag tag := fieldInfo.Tag
name := tag.Get("json") name := tag.Get("json")
if len(name) == 0 { if len(name) == 0 {
name = fieldInfo.Name continue
} }
field := elem.Field(i).Interface() field := elem.Field(i).Interface()
var valuedata string var valuedata string
@ -244,6 +244,7 @@ func (this *Encoder) EncoderToSliceString(v interface{}) (data []string, err err
} }
// vof = vof.Elem() // vof = vof.Elem()
if vof.Kind() == reflect.Slice { if vof.Kind() == reflect.Slice {
data = make([]string, vof.Len())
for i := 0; i < vof.Len(); i++ { for i := 0; i < vof.Len(); i++ {
value := vof.Index(i).Interface() value := vof.Index(i).Interface()
var valuedata string 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{UserId: session.GetUserId()} self := &pb.DB_FriendData{UserId: session.GetUserId()}
target := &pb.DB_FriendData{UserId: req.FriendId} 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 { if self == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData}
return return
} }
err = this.module.model_friend.GetObj(req.FriendId, target) err = this.module.model_friend.Get(req.FriendId, target)
if target == nil || err != nil { if target == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData}
return return
@ -72,7 +72,9 @@ func (this *ApiComp) Addblack(session comm.IUserSession, chk map[string]interfac
self.BlackIds = append(self.BlackIds, req.FriendId) 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 { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -12,7 +12,7 @@ func (this *ApiComp) Agree_Check(session comm.IUserSession, req *pb.Friend_Agree
self := &pb.DB_FriendData{UserId: session.GetUserId()} 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 { if self == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData}
return return
@ -71,7 +71,7 @@ func (this *ApiComp) Agree(session comm.IUserSession, chk map[string]interface{}
//双向添加:将自己加入到申请人的好友列表中 //双向添加:将自己加入到申请人的好友列表中
target := &pb.DB_FriendData{} 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 { if target == nil || err != nil {
code = pb.ErrorCode_FriendTargetNoData 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) 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 { if err != nil {
code = pb.ErrorCode_DBError 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 { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -14,14 +14,14 @@ func (this *ApiComp) Apply_Check(session comm.IUserSession, req *pb.Friend_Apply
target := &pb.DB_FriendData{UserId: req.FriendId} 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 { if self == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData}
return return
} }
//获取好友数据 //获取好友数据
err = this.module.model_friend.GetObj(req.FriendId, target) err = this.module.model_friend.Get(req.FriendId, target)
if target == nil || err != nil { if target == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendTargetNoData}
return return
@ -116,7 +116,9 @@ func (this *ApiComp) Apply(session comm.IUserSession, chk map[string]interface{}
} }
target.ApplyIds = append(target.ApplyIds, session.GetUserId()) 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 { if err != nil {
log.Errorf("firend Apply err:%v", err) log.Errorf("firend Apply err:%v", err)
code = pb.ErrorCode_FriendApplyError code = pb.ErrorCode_FriendApplyError

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) { 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{}) chk = make(map[string]interface{})
self := &pb.DB_FriendData{UserId: session.GetUserId()} 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 { if self == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData}
return return
@ -43,7 +43,9 @@ func (this *ApiComp) Delblack(session comm.IUserSession, chk map[string]interfac
//从黑名单列表中删除目标 //从黑名单列表中删除目标
self.BlackIds = utils.DeleteString(self.BlackIds, req.FriendId) 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 { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -12,7 +12,7 @@ func (this *ApiComp) Refuse_Check(session comm.IUserSession, req *pb.Friend_Refu
self := &pb.DB_FriendData{UserId: session.GetUserId()} 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 { if self == nil || err != nil {
code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData} code = comm.ErrorCode{Code: pb.ErrorCode_FriendSelfNoData}
return return
@ -66,7 +66,9 @@ func (this *ApiComp) Refuse(session comm.IUserSession, chk map[string]interface{
} }
//更新 //更新
if optNum > 0 { 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 { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -56,8 +56,8 @@ func (this *Mail) CreateNewMail(uId string) {
log.Error("create mail failed") log.Error("create mail failed")
} }
// 通知玩家 // 通知玩家
var _cache *pb.Cache_UserData var _cache = &pb.Cache_UserData{}
err = this.db_comp.Model_Comp.GetObj(uId, _cache) err = this.db_comp.Model_Comp.Get(uId, _cache)
if err == nil { if err == nil {
return return
} }

View File

@ -1,6 +1,7 @@
package modules package modules
import ( import (
"context"
"fmt" "fmt"
"go_dreamfactory/comm" "go_dreamfactory/comm"
"go_dreamfactory/lego/core" "go_dreamfactory/lego/core"
@ -16,7 +17,6 @@ import (
"go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo" "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 { func (this *Model_Comp) ukey(uid string) string {
return fmt.Sprintf("%s:%s", this.TableName, uid) 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) { 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 return err
} }
func (this *Model_Comp) UpdateModelLogs(table string, uID string, where bson.M, target interface{}) (err error) { func (this *Model_Comp) UpdateModelLogs(table string, uID string, where bson.M, target interface{}) (err error) {
data := &comm.Autogenerated{ data := &comm.Autogenerated{
@ -105,134 +107,216 @@ func (this *Model_Comp) UpdateModelLogs(table string, uID string, where bson.M,
return err return err
} }
//设置缓存JSON格式数据 //添加新的数据
//data 值允许protobuf格式的对象 func (this *Model_Comp) Add(uid string, data interface{}, attrs ...*cache.OperationAttr) (err error) {
// attrs 操作可选项目 eg.传入WithDisabledMgoLog() 表示关闭日志,否则开启;WithND() 传入表示插入操作不传表示更新前提不能传入传入WithDisabledMgoLog() if err = this.Redis.HMSet(this.ukey(uid), data); err != nil {
func (this *Model_Comp) SetObj(uid string, data proto.Message, attrs ...*cache.OperationAttr) error { return
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
} }
if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil {
return this.logOpt(uid, data, attrs...) 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}} func (this *Model_Comp) AddList(uid string, id string, data interface{}, attrs ...*cache.OperationAttr) (err error) {
//or &TestData{Name: "liwei1dao", Agr: 12, Sub: &TestAny{SubName: "test", Age: 20}} key := this.ukeylist(uid, id)
// attrs 操作可选项目 eg.传入WithDisabledMgoLog() 表示关闭日志,否则开启;WithND() 传入表示插入操作不传表示更新前提不能传入传入WithDisabledMgoLog() if err = this.Redis.HMSet(key, data); err != nil {
//如果更新数据uid作为where条件之一如果检索结果不能确定唯一此时data 必需是map[string]interface{}类型必需包含_id 字段 return
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
} }
if err = this.Redis.HSet(this.ukey(uid), id, key); err != nil {
return this.logOpt(uid, data, attrs...) 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 作为主键
//如果更新数据uid作为where条件之一如果检索结果不能确定唯一此时data 必需是map[string]interface{}类型必需包含_id 字段 func (this *Model_Comp) Change(uid string, data map[string]interface{}, attrs ...*cache.OperationAttr) (err error) {
func (this *Model_Comp) SetH(uid string, field string, data interface{}, attrs ...*cache.OperationAttr) error { if err = this.Redis.HMSet(this.ukey(uid), data); err != nil {
err := this.Redis.HSet(this.ukey(uid), field, data) return
if err != nil {
log.Errorf("SetH err %v", err)
return err
} }
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数据 //修改数据多个字段 uid 作为主键
func (this *Model_Comp) GetObj(uid string, v proto.Message) error { func (this *Model_Comp) ChangeList(uid string, _id string, data map[string]interface{}, attrs ...*cache.OperationAttr) (err error) {
err := this.Redis.Get(this.ukey(uid), v) if err = this.Redis.HMSet(this.ukeylist(uid, _id), data); err != nil {
if err != nil { return
if err == redis.RedisNil { }
//query from mgo if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_EXPIRE).Unwrap_Or(nil); ret != nil {
err = this.DB.FindOne(core.SqlTable(this.TableName), bson.M{"_id": uid}).Decode(v) this.Redis.Expire(this.ukey(uid), ret.(time.Duration))
if err != nil { }
//no record if ret := cache.OperationAttrs(attrs).Find(cache.ATTR_MGOLOG).Unwrap_Or(nil); ret == nil {
if err == mongo.ErrNoDocuments { err = this.UpdateModelLogs(this.TableName, uid, bson.M{"_id": _id, "uid": uid}, data)
_, err = this.DB.InsertOne(core.SqlTable(this.TableName), v) }
if err != nil { return nil
log.Errorf("insert err: %v", err) }
return err
} //读取全部数据
//set cache func (this *Model_Comp) Get(uid string, data interface{}) (err error) {
return this.SetObj(uid, v, cache.WithND()) 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 return err
} }
//获取对象所有字段数据 //读取单个数据中 多个字段数据
//data类型map或protobuf func (this *Model_Comp) GetFields(uid string, data interface{}, fields ...string) (err error) {
func (this *Model_Comp) GetHM(uid string, data interface{}) error { this.Redis.HMGet(this.ukey(uid), data, fields...)
ok, err := this.Redis.ExistsKey(this.ukey(uid)) 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 { if err != nil {
log.Errorf("key no exist %v", this.ukey(uid))
return err return err
} }
if ok { err = this.DeleteModelLogs(this.TableName, uid, bson.M{"uid": uid})
return this.Redis.HGetAll(this.ukey(uid), data) return nil
} else { }
filter := bson.M{"uid": uid}
c, err2 := this.DB.Find(core.SqlTable(this.TableName), filter) //删除多条数据
if err2 != nil { func (this *Model_Comp) DelListlds(uid string, ids ...string) (err error) {
log.Errorf("GetHM-find err:%v", err) listkey := this.ukey(uid)
return err 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())
} }
if err = this.Redis.HDel(listkey, ids...); err == nil {
} err = this.DeleteModelLogs(this.TableName, uid, bson.M{"_id": bson.M{"$in": ids}})
//获取字段数据 缓存存储的数据为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
} }
return
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)
} }
//日志操作可选项 //日志操作可选项

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) { func (this *Model_Pack_Comp) Pack_QueryUserPack(uId string) (itmes []*pb.DB_UserItemData, err error) {
var ( itmes = make([]*pb.DB_UserItemData, 0)
data map[string]*pb.DB_UserItemData = make(map[string]*pb.DB_UserItemData) err = this.GetList(uId, &itmes)
)
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
// }
// }
return return
} }
///查询用户指定格子的物品数据 ///查询用户指定格子的物品数据
func (this *Model_Pack_Comp) Pack_QueryUserPackByGridId(uId string, grid string) (itme *pb.DB_UserItemData, err error) { func (this *Model_Pack_Comp) Pack_QueryUserPackByGridId(uId string, grid string) (itme *pb.DB_UserItemData, err error) {
itme = &pb.DB_UserItemData{} itme = &pb.DB_UserItemData{}
err = this.GetH(uId, grid, itme) err = this.GetListObj(uId, grid, itme)
return
}
// var ( //更新用户的背包信息
// itmes []*pb.DB_UserItemData func (this *Model_Pack_Comp) Pack_AddUserPack(uId string, itmes ...*pb.DB_UserItemData) (err error) {
// temp map[string]interface{} for _, v := range itmes {
// ) this.AddList(uId, v.GridId, v)
// itme = &pb.DB_UserItemData{} }
// if err = this.Redis.HGet(fmt.Sprintf(Redis_PackCache, uId), grid, itme); err == nil { return
// return }
// } else if err == redis.RedisNil {
// if itmes, err = this.module.db_comp.Pack_QueryUserPack(uId); err == nil { //更新用户的背包信息
// temp = make(map[string]interface{}) func (this *Model_Pack_Comp) Pack_DelUserPack(uId string, ids ...string) (err error) {
// for _, v := range itmes { err = this.DelListlds(uId, ids...)
// 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
// }
// }
return return
} }
//更新用户的背包信息 //更新用户的背包信息
func (this *Model_Pack_Comp) Pack_UpdateUserPack(uId string, itmes ...*pb.DB_UserItemData) (err error) { 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 { 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 return
} }
//更新用户的背包信息 //更新用户的背包信息
func (this *Model_Pack_Comp) Pack_DeleteUserPack(uId string, gridIds ...string) (err error) { 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.DelListlds(uId, gridIds...)
err = this.module.db_comp.Pack_DeleteGridToUserPack(uId, gridIds...)
}
return 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) { func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, addnum int32) (err error) {
var ( var (
itmes []*pb.DB_UserItemData itmes []*pb.DB_UserItemData
modifys []*pb.DB_UserItemData add []*pb.DB_UserItemData
del []string
update []*pb.DB_UserItemData
leftnum int64 leftnum int64
) )
if addnum == 0 { 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 { if itmes, err = this.Pack_QueryUserPack(uId); err != nil {
return return
} }
modifys, leftnum = this.pack_addItemToUserPack(itmes, itemId, addnum) add, update, del, leftnum = this.pack_addItemToUserPack(itmes, itemId, addnum)
if leftnum < 0 { if leftnum < 0 {
err = ItemNotEnoughError err = ItemNotEnoughError
return return
@ -163,24 +113,39 @@ func (this *Model_Pack_Comp) Pack_AddItemToUserPack(uId string, itemId int32, ad
err = PackGridNumUpper err = PackGridNumUpper
return 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 return
} }
///添加或则减少多个物品到用户背包 ///添加或则减少多个物品到用户背包
func (this *Model_Pack_Comp) Pack_AddItemsToUserPack(uId string, items map[int32]int32) (err error) { func (this *Model_Pack_Comp) Pack_AddItemsToUserPack(uId string, items map[int32]int32) (err error) {
var ( var (
itmes []*pb.DB_UserItemData itmes []*pb.DB_UserItemData
modifys []*pb.DB_UserItemData add []*pb.DB_UserItemData
tempmodifys []*pb.DB_UserItemData del []string
leftnum int64 update []*pb.DB_UserItemData
iskeep bool leftnum int64
) )
if itmes, err = this.Pack_QueryUserPack(uId); err != nil { if itmes, err = this.Pack_QueryUserPack(uId); err != nil {
return return
} }
for k, v := range items { 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 { if leftnum < 0 {
err = ItemNotEnoughError err = ItemNotEnoughError
return return
@ -188,20 +153,22 @@ func (this *Model_Pack_Comp) Pack_AddItemsToUserPack(uId string, items map[int32
err = PackGridNumUpper err = PackGridNumUpper
return return
} }
for _, v1 := range tempmodifys { if len(add) > 0 {
iskeep = false if err = this.Pack_AddUserPack(uId, add...); err != nil {
for _, v2 := range modifys { return
if v1.GridId == v2.GridId {
iskeep = true
}
} }
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 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 ( var (
num int64 num int64
isNew bool isNew bool
@ -251,7 +218,9 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData,
} }
isNew = true isNew = true
leftnum = int64(addnum) 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 { for _, v := range items {
if !v.IsEmpty && v.ItemId == itemId { if !v.IsEmpty && v.ItemId == itemId {
isNew = false isNew = false
@ -260,30 +229,30 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData,
leftnum += int64(v.Amount) leftnum += int64(v.Amount)
v.Amount = 0 v.Amount = 0
v.IsEmpty = true v.IsEmpty = true
modifys = append(modifys, v) del = append(del, v.GridId)
} else if num > 0 && num < int64(v.Amount) { } else if num > 0 && num < int64(v.Amount) {
leftnum = 0 leftnum = 0
v.Amount = uint32(num) v.Amount = uint32(num)
modifys = append(modifys, v) update = append(update, v)
break break
} else if num > 0 && num > int64(v.Amount) { } else if num > 0 && num > int64(v.Amount) {
if num <= GridCapMaxNum { if num <= GridCapMaxNum {
leftnum = 0 leftnum = 0
v.Amount = uint32(num) v.Amount = uint32(num)
modifys = append(modifys, v) update = append(update, v)
break break
} else { } else {
if v.Amount < GridCapMaxNum { if v.Amount < GridCapMaxNum {
leftnum = int64(num - GridCapMaxNum) leftnum = int64(num - GridCapMaxNum)
v.Amount = uint32(GridCapMaxNum) v.Amount = uint32(GridCapMaxNum)
modifys = append(modifys, v) update = append(update, v)
} }
} }
} else if num == 0 { } else if num == 0 {
leftnum = 0 leftnum = 0
v.Amount = 0 v.Amount = 0
v.IsEmpty = true 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.ItemId = itemId
v.Amount = uint32(leftnum) v.Amount = uint32(leftnum)
leftnum = 0 leftnum = 0
modifys = append(modifys, v) update = append(update, v)
break break
} else { } else {
leftnum -= GridCapMaxNum leftnum -= GridCapMaxNum
v.IsEmpty = false v.IsEmpty = false
v.ItemId = itemId v.ItemId = itemId
v.Amount = uint32(GridCapMaxNum) 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, IsNewItem: isNew,
} }
items = append(items, grid) items = append(items, grid)
modifys = append(modifys, grid) add = append(add, grid)
leftnum = 0 leftnum = 0
break break
} else { } else {
@ -333,7 +302,7 @@ func (this *Model_Pack_Comp) pack_addItemToUserPack(items []*pb.DB_UserItemData,
IsNewItem: isNew, IsNewItem: isNew,
} }
items = append(items, grid) items = append(items, grid)
modifys = append(modifys, grid) add = append(add, grid)
index++ index++
} }
if index > GridMaxNUm { //格子已达上限 if index > GridMaxNUm { //格子已达上限

View File

@ -22,8 +22,8 @@ type Pack struct {
modules.ModuleBase modules.ModuleBase
api_comp *Api_Comp api_comp *Api_Comp
model_pack_comp *Model_Pack_Comp model_pack_comp *Model_Pack_Comp
db_comp *DB_Comp // db_comp *DB_Comp
configure_comp *Configure_Comp configure_comp *Configure_Comp
} }
//模块名称 //模块名称

View File

@ -16,10 +16,7 @@ import (
"testing" "testing"
"time" "time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive" "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 { func newService(ops ...rpcx.Option) core.IService {
@ -78,9 +75,13 @@ func TestMain(m *testing.M) {
func Test_Log(t *testing.T) { func Test_Log(t *testing.T) {
// data, _ := ptypes.MarshalAny(&pb.Pack_Getlist_Req{}) // data, _ := ptypes.MarshalAny(&pb.Pack_Getlist_Req{})
// s_gateComp.ReceiveMsg(context.Background(), &pb.AgentMessage{Method: "pack.getlist", Message: data}, &pb.RPCMessageReply{}) // 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") func Test_Pack_UpdateGridToUserPack(t *testing.T) {
// log.Debugf("item:%v err:%v", items, err)
uid := "0_62a9afd994fe03b7aaee6773" uid := "0_62a9afd994fe03b7aaee6773"
Pack_UpdateGridToUserPack( Pack_UpdateGridToUserPack(
uid, uid,
@ -135,19 +136,24 @@ func Test_Log(t *testing.T) {
//更新背包格子数据 //更新背包格子数据
func Pack_UpdateGridToUserPack(uId string, grids ...*pb.DB_UserItemData) (err error) { 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 { for i, v := range grids {
models[i] = mongo.NewUpdateOneModel().SetFilter(bson.M{"_id": v.GridId}).SetUpdate( data[i] = v
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)) module.model_pack_comp.DB.InsertMany(DB_PackTable, data)
return return
} }

View File

@ -25,13 +25,13 @@ func (this *Api_Comp) Create(session comm.IUserSession, result map[string]interf
// update := map[string]interface{}{ // update := map[string]interface{}{
// "name": req.NickName, // "name": req.NickName,
// } // }
err := this.module.modelUser.GetObj(session.GetUserId(), self) err := this.module.modelUser.Get(session.GetUserId(), self)
if err != nil { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return
} }
self.Name = req.NickName self.Name = req.NickName
err = this.module.modelUser.SetObj(session.GetUserId(), self) err = this.module.modelUser.Get(session.GetUserId(), self)
if err != nil { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -69,10 +69,10 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa
user.Createip = session.GetIP() user.Createip = session.GetIP()
//缓存user session //缓存user session
err = this.module.modelSession.SetObj(user.Uid, &pb.Cache_UserData{ err = this.module.modelSession.Change(user.Uid, map[string]interface{}{
Uid: user.Uid, "uId": user.Uid,
SessionId: session.GetSessionId(), "sessionId": session.GetSessionId(),
GatewayServiceId: session.GetGatewayServiceId(), "gatewayServiceId": session.GetGatewayServiceId(),
}, },
cache.WithExpire(time.Hour*12), cache.WithExpire(time.Hour*12),
cache.WithDisabledMgoLog()) cache.WithDisabledMgoLog())
@ -82,7 +82,7 @@ func (this *Api_Comp) Login(session comm.IUserSession, result map[string]interfa
} }
//缓存user //缓存user
err = this.module.modelUser.SetObj(user.Uid, user) err = this.module.modelUser.Add(user.Uid, user, cache.WithDisabledMgoLog())
if err != nil { if err != nil {
code = pb.ErrorCode_DBError code = pb.ErrorCode_DBError
return return

View File

@ -26,14 +26,14 @@ type DB_UserItemData struct {
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
GridId string `protobuf:"bytes,1,opt,name=GridId,proto3" json:"GridId"` //背包格子Id 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"` //用户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"` //是否是空格子 IsEmpty bool `protobuf:"varint,3,opt,name=isEmpty,proto3" json:"isEmpty" bson:"isEmpty"` // 是否是空格子
ItemId int32 `protobuf:"varint,4,opt,name=ItemId,proto3" json:"ItemId"` //存放物品的Id 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"` //存放物品的数量 Amount uint32 `protobuf:"varint,5,opt,name=amount,proto3" json:"amount" bson:"amount"` // 存放物品的数量
CTime int64 `protobuf:"varint,6,opt,name=CTime,proto3" json:"CTime"` //物品获取时间 CTime int64 `protobuf:"varint,6,opt,name=cTime,proto3" json:"cTime" bson:"cTime"` // 物品获取时间
ETime int64 `protobuf:"varint,7,opt,name=ETime,proto3" json:"ETime"` //物品过期时间 ETime int64 `protobuf:"varint,7,opt,name=eTime,proto3" json:"eTime" bson:"eTime"` // 物品过期时间
IsNewItem bool `protobuf:"varint,8,opt,name=IsNewItem,proto3" json:"IsNewItem"` //是否是新的 IsNewItem bool `protobuf:"varint,8,opt,name=isNewItem,proto3" json:"isNewItem" bson:"isNewItem"` // 是否是新的
} }
func (x *DB_UserItemData) Reset() { 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{ var file_pack_pack_db_proto_rawDesc = []byte{
0x0a, 0x12, 0x70, 0x61, 0x63, 0x6b, 0x2f, 0x70, 0x61, 0x63, 0x6b, 0x5f, 0x64, 0x62, 0x2e, 0x70, 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, 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, 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, 0x47, 0x72, 0x69, 0x64, 0x49, 0x64, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x67, 0x72, 0x69, 0x64, 0x49, 0x64,
0x12, 0x10, 0x0a, 0x03, 0x55, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x55, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75,
0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x49, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x18, 0x03, 0x20, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x69, 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, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 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, 0x69, 0x74, 0x65, 0x6d, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x69, 0x74,
0x65, 0x6d, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x65, 0x6d, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05,
0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x41, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x61, 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, 0x63, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x63, 0x54, 0x69,
0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x45, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 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, 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, 0x49, 0x73, 0x4e, 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, 0x65, 0x77, 0x49, 0x74, 0x65, 0x6d, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x3b, 0x70, 0x62, 0x62, 0x06,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
} }

View File

@ -4,12 +4,12 @@ option go_package = ".;pb";
// //
message DB_UserItemData { message DB_UserItemData {
string GridId = 1; //Id string gridId = 1; //@go_tags(`bson:"_id"`) Id
string UId = 2; //id string uId = 2; //@go_tags(`bson:"uId"`) id
bool IsEmpty = 3; // bool isEmpty = 3; //@go_tags(`bson:"isEmpty"`)
int32 ItemId = 4; //Id int32 itemId = 4; //@go_tags(`bson:"itemId"`) Id
uint32 Amount = 5; // uint32 amount = 5; //@go_tags(`bson:"amount"`)
int64 CTime = 6; // int64 cTime = 6; //@go_tags(`bson:"cTime"`)
int64 ETime = 7; // int64 eTime = 7; //@go_tags(`bson:"eTime"`)
bool IsNewItem = 8; // bool isNewItem = 8; //@go_tags(`bson:"isNewItem"`)
} }