Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"cache.go",
"dao.go",
"mysql.go",
"redis.go",
],
importpath = "go-common/app/service/live/xuser/dao/guard",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/live/xuser/conf:go_default_library",
"//app/service/live/xuser/model:go_default_library",
"//app/service/live/xuser/model/dhh:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/stat/prom:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,48 @@
package guard
import (
"context"
"fmt"
"go-common/library/cache/redis"
"go-common/library/log"
)
// redis cache
const (
_lockKey = "saveGuard:%s"
_cacheKeyUid = "live_user:guard:uid:v1:%d"
_cacheKeyTargetId = "live_user:guard:target_id:v1:%d"
)
// LockOrder lock for same order
func (d *GuardDao) LockOrder(ctx context.Context, orderID string) (ok bool, err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
_, err = redis.String(conn.Do("SET", fmt.Sprintf(_lockKey, orderID), 1, "EX", 3*86400, "NX"))
if err == redis.ErrNil {
log.Info("LockOrder(%s) is ErrNil!", orderID)
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// UnlockOrder release lock for same order
func (d *GuardDao) UnlockOrder(ctx context.Context, orderID string) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
_, err = redis.String(conn.Do("DEL", fmt.Sprintf(_lockKey, orderID)))
return
}
// ClearCache delete cache for guard
func (d *GuardDao) ClearCache(ctx context.Context, uid int64, ruid int64) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
_, err = redis.String(conn.Do("DEL", fmt.Sprintf(_cacheKeyUid, uid)))
_, err = redis.String(conn.Do("DEL", fmt.Sprintf(_cacheKeyTargetId, ruid)))
return
}

View File

@@ -0,0 +1,47 @@
package guard
import (
"context"
"go-common/app/service/live/xuser/conf"
"go-common/library/cache/redis"
xsql "go-common/library/database/sql"
)
// GuardDao vip dao
type GuardDao struct {
c *conf.Config
db *xsql.DB
redis *redis.Pool
}
// NewGuardDao init mysql db
func NewGuardDao(c *conf.Config) (dao *GuardDao) {
dao = &GuardDao{
c: c,
db: xsql.NewMySQL(c.LiveAppMySQL),
redis: redis.NewPool(c.GuardRedis),
}
return
}
// Close close the resource.
func (d *GuardDao) Close() {
d.db.Close()
d.redis.Close()
}
// Ping dao ping
func (d *GuardDao) Ping(ctx context.Context) error {
// TODO: add mc,redis... if you use
return nil
}
func (d *GuardDao) getExpire() (respExpire int32) {
if t := conf.Conf.UserDaHangHaiExpire; t != nil {
respExpire = t.ExpireTime
} else {
respExpire = _emptyExpire
}
return
}

View File

@@ -0,0 +1,197 @@
package guard
import (
"context"
"fmt"
"go-common/library/xstr"
"time"
confm "go-common/app/service/live/xuser/conf"
"go-common/app/service/live/xuser/model"
dhhm "go-common/app/service/live/xuser/model/dhh"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_guardTable = "ap_user_privilege"
)
var (
// add guard info
_addGuardInfo = "REPLACE INTO `%s` (`uid`,`target_id`,`privilege_type`,`start_time`,`expired_time`) VALUES(?,?,?,?,?);"
// get guard info
_getGuardInfo = "SELECT `id`,`uid`,`target_id`,`privilege_type`,`start_time`,`expired_time` FROM `%s` WHERE `uid`=? AND `expired_time`>=? ORDER BY `privilege_type` ASC;"
// get guard info
_getGuardInfo2 = "SELECT `id`,`uid`,`target_id`,`privilege_type`,`start_time`,`expired_time` FROM `%s` WHERE `uid`=? AND `target_id`=? AND `expired_time`>=? ORDER BY `privilege_type` ASC;"
// update guard info
_updGuardInfo = "UPDATE `%s` SET `expired_time`=date_add(expired_time, interval ? day) WHERE `uid`=? AND `target_id`=? AND `expired_time`>=? AND `privilege_type`%s?"
// upsert guard info
_upsertGuardInfo = "INSERT INTO `%s` (`uid`,`target_id`,`privilege_type`,`start_time`,`expired_time`) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE `start_time`=?,`expired_time`=?;"
// 查询大航海信息
_selUID = "SELECT id,uid,target_id,privilege_type,start_time,expired_time,ctime,utime FROM ap_user_privilege where uid IN (%s) AND expired_time >= '%s' "
_selAnchorUID = "SELECT id,uid,target_id,privilege_type,start_time,expired_time,ctime,utime FROM ap_user_privilege where target_id IN (%s) AND expired_time >= '%s' "
_errorDBLogPrefix = "xuser.dahanghai.dao.mysql|"
)
// GetByUIDs 批量查询
func (d *GuardDao) GetByUIDs(c context.Context, uids []int64) (dhhs []*dhhm.DHHDB, err error) {
reqStartTime := confm.RecordTimeCost()
dhhs = make([]*dhhm.DHHDB, 0)
tm := time.Now()
timeNow := tm.Format("2006-1-2 15:04:05")
rows, err1 := d.db.Query(c, fmt.Sprintf(_selUID, xstr.JoinInts(uids), timeNow))
if err1 != nil {
reqAfterTime := confm.RecordTimeCost()
err = err1
log.Error(_errorDBLogPrefix+confm.GetFromDHHDBError+"|GetByUIDs err: %v|cost:%dms", err, reqAfterTime-reqStartTime)
return
}
for rows.Next() {
ele := &dhhm.DHHDB{}
if err = rows.Scan(&ele.ID, &ele.UID, &ele.TargetId, &ele.PrivilegeType, &ele.StartTime, &ele.ExpiredTime, &ele.Ctime, &ele.Utime); err != nil {
log.Error(_errorDBLogPrefix+confm.ScanFromDHHDBError+"|GetByUIDs rows.Scan err: %v", err)
return
}
dhhs = append(dhhs, ele)
}
return
}
// GetByUIDsWithMap 批量查询
func (d *GuardDao) GetByUIDsWithMap(c context.Context, uids []int64) (dhhs map[int64][]*dhhm.DHHDB, err error) {
reqStartTime := confm.RecordTimeCost()
dhhs = make(map[int64][]*dhhm.DHHDB)
tm := time.Now()
timeNow := tm.Format("2006-1-2 15:04:05")
rows, err1 := d.db.Query(c, fmt.Sprintf(_selUID, xstr.JoinInts(uids), timeNow))
if err1 != nil {
reqAfterTime := confm.RecordTimeCost()
err = err1
log.Error(_errorDBLogPrefix+confm.GetFromDHHDBError+"|GetByUIDs err: %v|cost:%dms", err, reqAfterTime-reqStartTime)
return
}
for rows.Next() {
ele := &dhhm.DHHDB{}
if err = rows.Scan(&ele.ID, &ele.UID, &ele.TargetId, &ele.PrivilegeType, &ele.StartTime, &ele.ExpiredTime, &ele.Ctime, &ele.Utime); err != nil {
log.Error(_errorDBLogPrefix+confm.ScanFromDHHDBError+"|GetByUIDs rows.Scan err: %v", err)
return
}
if _, exist := dhhs[ele.UID]; !exist {
dhhs[ele.UID] = make([]*dhhm.DHHDB, 0)
}
dhhs[ele.UID] = append(dhhs[ele.UID], ele)
}
return
}
// GetByAnchorUIDs 批量查询
func (d *GuardDao) GetByAnchorUIDs(c context.Context, uids []int64) (dhhs []*dhhm.DHHDB, err error) {
reqStartTime := confm.RecordTimeCost()
dhhs = make([]*dhhm.DHHDB, 0)
tm := time.Now()
timeNow := tm.Format("2006-1-2 15:04:05")
rows, err1 := d.db.Query(c, fmt.Sprintf(_selAnchorUID, xstr.JoinInts(uids), timeNow))
if err1 != nil {
reqAfterTime := confm.RecordTimeCost()
err = err1
log.Error(_errorDBLogPrefix+confm.GetFromDHHDBError+"|GetByUIDs err: %v|cost:%dms", err, reqAfterTime-reqStartTime)
return
}
for rows.Next() {
ele := &dhhm.DHHDB{}
if err = rows.Scan(&ele.ID, &ele.UID, &ele.TargetId, &ele.PrivilegeType, &ele.StartTime, &ele.ExpiredTime, &ele.Ctime, &ele.Utime); err != nil {
log.Error(_errorDBLogPrefix+confm.ScanFromDHHDBError+"|GetByUIDs rows.Scan err: %v", err)
return
}
dhhs = append(dhhs, ele)
}
return
}
// GetGuardByUID get guard info by uid
func (d *GuardDao) GetGuardByUID(ctx context.Context, uid int64) (info []*model.GuardInfo, err error) {
sql := fmt.Sprintf(_getGuardInfo, _guardTable)
rows, err := d.db.Query(ctx, sql, uid, time.Now().Format("2006-01-02 15:04:05"))
if err != nil {
log.Error("[dao.guard.mysql|GetGuardByUID] get user guard record error(%v), uid(%d)", err, uid)
return nil, err
}
defer rows.Close()
for rows.Next() {
var inf model.GuardInfo
err = rows.Scan(&inf.Id, &inf.Uid, &inf.TargetId, &inf.PrivilegeType, &inf.StartTime, &inf.ExpiredTime)
if err != nil {
log.Error("[dao.guard.mysql|GetGuardByUID] scan user guard record error(%v), uid(%d)", err, uid)
return nil, err
}
info = append(info, &inf)
}
return
}
// GetGuardByUIDRuid get guard info by uid and ruid
func (d *GuardDao) GetGuardByUIDRuid(ctx context.Context, uid int64, ruid int64) (info []*model.GuardInfo, err error) {
sql := fmt.Sprintf(_getGuardInfo2, _guardTable)
rows, err := d.db.Query(ctx, sql, uid, ruid, time.Now().Format("2006-01-02 15:04:05"))
if err != nil {
log.Error("[dao.guard.mysql|GetGuardByUIDRuid] get user guard record error(%v), uid(%d), ruid(%d)", err, uid, ruid)
return nil, err
}
defer rows.Close()
for rows.Next() {
var inf model.GuardInfo
err = rows.Scan(&inf.Id, &inf.Uid, &inf.TargetId, &inf.PrivilegeType, &inf.StartTime, &inf.ExpiredTime)
if err != nil {
log.Error("[dao.guard.mysql|GetGuardByUIDRuid] scan user guard record error(%v), uid(%d), ruid(%d)", err, uid, ruid)
return nil, err
}
info = append(info, &inf)
}
return
}
// AddGuard insert guard
func (d *GuardDao) AddGuard(ctx context.Context, req *model.GuardBuy) (err error) {
sql := fmt.Sprintf(_addGuardInfo, _guardTable)
now := time.Now()
endTime := time.Date(now.Year(), now.Month(), now.Day(), int(23), int(59), int(59), int(999), time.Local).AddDate(0, 0, req.Num*30)
res, err := d.db.Exec(ctx, sql, req.Uid, req.Ruid, req.GuardLevel, now.Format("2006-01-02 15:04:05"), endTime.Format("2006-01-02 15:04:05"))
if err != nil {
// unique key exists error
log.Error("[dao.guard.mysql|AddGuard] add user guard record error(%v), req(%v)", err, req)
return
}
if _, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
log.Error("[dao.guard.mysql|AddGuard] get last insert id error(%v), req(%v)", err, req)
}
return
}
// UpdateGuard update guard info
func (d *GuardDao) UpdateGuard(ctx context.Context, req *model.GuardBuy, cond string) (err error) {
sql := fmt.Sprintf(_updGuardInfo, _guardTable, cond)
_, err = d.db.Exec(ctx, sql, req.Num*30, req.Uid, req.Ruid, time.Now().Format("2006-01-02 15:04:05"), req.GuardLevel)
if err != nil {
log.Error("[dao.guard.mysql|UpdateGuard] update user guard record error(%v), req(%v)", err, req)
return
}
return
}
// UpsertGuard upsert guard info
func (d *GuardDao) UpsertGuard(ctx context.Context, req *model.GuardBuy, expiredTime string) (err error) {
sql := fmt.Sprintf(_upsertGuardInfo, _guardTable)
now := time.Now()
_, err = d.db.Exec(ctx, sql, req.Uid, req.Ruid, req.GuardLevel, now.Format("2006-01-02 15:04:05"), expiredTime, now.Format("2006-01-02 15:04:05"), expiredTime)
if err != nil {
log.Error("[dao.guard.mysql|UpsertGuard] upsert user guard record error(%v), req(%v)", err, req)
return
}
return
}

View File

@@ -0,0 +1,361 @@
package guard
import (
"context"
"encoding/json"
"github.com/pkg/errors"
dahanghaiModel "go-common/app/service/live/xuser/model/dhh"
gmc "go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/log"
"go-common/library/stat/prom"
"math/rand"
"strconv"
"time"
)
// redis cache
const (
_prefixUID = "live_user:guard:uid:v1:" // 用户侧key
_prefixTopList = "GOVERNOR_SHOW_TID:" // 最近购买总督key
_prefixAnchorID = "live_user:guard:target_id:v1:" // 主播侧key
_emptyExpire = 3600
_errorRedisLogPrefix = "xuser.dahanghai.dao.redis"
_promGetSuccess = "xuser_dahanghai_redis:获取用户大航海cache成功"
_promDelSuccess = "xuser_dahanghai_redis:成功删除用户大航海cache"
_promDelErr = "xuser_dahanghai_redis:删除用户大航海cache失败"
_promGetErr = "xuser_dahanghai_redis:批量获取用户大航海key失败"
// _promScanErr = "xuser_dahanghai_redis:解析用户大航海key失败"
)
var (
errorsCount = prom.BusinessErrCount
infosCount = prom.BusinessInfoCount
cacheHitCount = prom.CacheHit
cacheMissCount = prom.CacheMiss
)
// PromError prometheus error count.
func PromError(name string) {
errorsCount.Incr(name)
}
// PromInfo prometheus info count.
func PromInfo(name string) {
infosCount.Incr(name)
}
// PromCacheHit prometheus cache hit count.
func PromCacheHit(name string) {
cacheHitCount.Incr(name)
}
// PromCacheMiss prometheus cache hit count.
func PromCacheMiss(name string) {
cacheMissCount.Incr(name)
}
func dahanghaiUIDKey(mid int64) string {
return _prefixUID + strconv.FormatInt(mid, 10)
}
func guardAnchorUIDKey(mid int64) string {
return _prefixAnchorID + strconv.FormatInt(mid, 10)
}
func recentGuardTopKey(mid int64) string {
return _prefixTopList + strconv.FormatInt(mid, 10)
}
// SetDHHListCache ... 批量设置用户守护cache
func (d *GuardDao) SetDHHListCache(c context.Context, dhhList []dahanghaiModel.DaHangHaiRedis2, uid int64) (err error) {
return d.setDHHListCache(c, dhhList, uid)
}
// SetAnchorGuardListCache ... 批量设置主播维度守护信息cache
func (d *GuardDao) SetAnchorGuardListCache(c context.Context, dhhList []dahanghaiModel.DaHangHaiRedis2, uid int64) (err error) {
return d.setAnchorGuardListCache(c, dhhList, uid)
}
// DelDHHFromRedis 删除获取用户守护cache,不支持批量
func (d *GuardDao) DelDHHFromRedis(c context.Context, mid int64) (err error) {
return d.delDHHFromRedis(c, dahanghaiUIDKey(mid))
}
// GetUIDAllGuardFromRedis 获取单个用户的全量守护信息
func (d *GuardDao) GetUIDAllGuardFromRedis(ctx context.Context, mids []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
return d.getUIDAllGuardFromRedis(ctx, mids)
}
// GetUIDAllGuardFromRedisBatch 获取批量用户的全量守护信息
func (d *GuardDao) GetUIDAllGuardFromRedisBatch(ctx context.Context, mids []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
return d.getUIDAllGuardFromRedisBatch(ctx, mids)
}
// GetAnchorAllGuardFromRedis 获取单个主播的全量被守护信息(同一个主播仅获取最高级别)
func (d *GuardDao) GetAnchorAllGuardFromRedis(ctx context.Context, anchorUIDs []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
return d.getAnchorAllGuardFromRedis(ctx, anchorUIDs)
}
// GetGuardTopListCache 获取单个用户的全量守护信息
func (d *GuardDao) GetGuardTopListCache(ctx context.Context, uid int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
return d.getGuardTopListCache(ctx, uid)
}
// GetAnchorRecentTopGuardCache 获取单个主播最近的总督信息
func (d *GuardDao) GetAnchorRecentTopGuardCache(ctx context.Context, uid int64) (resp map[int64]int64, err error) {
return d.getAnchorRecentTopGuardCache(ctx, uid)
}
func (d *GuardDao) getGuardTopListCache(ctx context.Context, uid int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
return
}
// getUIDAllGuardFromRedis 批量获取用户cache
func (d *GuardDao) getUIDAllGuardFromRedis(ctx context.Context, mids []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
var (
conn = d.redis.Get(ctx)
args = redis.Args{}
cacheResult [][]byte
)
defer conn.Close()
for _, uid := range mids {
args = args.Add(dahanghaiUIDKey(uid))
}
if cacheResult, err = redis.ByteSlices(conn.Do("MGET", args...)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
PromError(_promGetErr)
log.Error(_errorRedisLogPrefix+"|conn.MGET(%v) error(%v)", args, err)
err = errors.Wrapf(err, "redis.StringMap(conn.Do(MGET,%v)", args)
}
return
}
dhhList = make([]*dahanghaiModel.DaHangHaiRedis2, 0)
dhhListSingle := &dahanghaiModel.DaHangHaiRedis2{}
if len(cacheResult) > 0 {
for k, v := range cacheResult {
if v == nil {
return nil, nil
}
if len(v) > 0 {
if err = json.Unmarshal([]byte(v), &dhhList); err != nil {
if err = json.Unmarshal([]byte(v), &dhhListSingle); err != nil {
log.Error("[dao.dahanghai.cache|GetDHHFromRedis] json.Unmarshal rawInfo error(%v), uid(%d), reply(%s)",
err, k, v)
return nil, nil
}
dhhList = append(dhhList, dhhListSingle)
}
}
}
}
PromInfo(_promGetSuccess)
return
}
// getUIDAllGuardFromRedis 批量获取用户cache
func (d *GuardDao) getUIDAllGuardFromRedisBatch(ctx context.Context, mids []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
var (
conn = d.redis.Get(ctx)
args = redis.Args{}
cacheResult [][]byte
)
defer conn.Close()
for _, uid := range mids {
args = args.Add(dahanghaiUIDKey(uid))
}
if cacheResult, err = redis.ByteSlices(conn.Do("MGET", args...)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
PromError(_promGetErr)
log.Error(_errorRedisLogPrefix+"|conn.MGET(%v) error(%v)", args, err)
err = errors.Wrapf(err, "redis.StringMap(conn.Do(MGET,%v)", args)
}
return
}
dhhList = make([]*dahanghaiModel.DaHangHaiRedis2, 0)
if len(cacheResult) > 0 {
for k, v := range cacheResult {
if v == nil {
continue
}
dhhListLoop := make([]*dahanghaiModel.DaHangHaiRedis2, 0)
dhhListSingle := &dahanghaiModel.DaHangHaiRedis2{}
if len(v) > 0 {
if err = json.Unmarshal([]byte(v), &dhhListLoop); err != nil {
if err = json.Unmarshal([]byte(v), &dhhListSingle); err != nil {
log.Error("[dao.dahanghai.cache|GetDHHFromRedis] json.Unmarshal rawInfo error(%v), uid(%d), reply(%s)",
err, k, v)
return nil, nil
}
dhhList = append(dhhList, dhhListSingle)
} else {
dhhList = append(dhhList, dhhListLoop...)
}
}
}
}
PromInfo(_promGetSuccess)
return
}
// getAnchorAllGuardFromRedis 批量获取用户cache
func (d *GuardDao) getAnchorAllGuardFromRedis(ctx context.Context, mids []int64) (dhhList []*dahanghaiModel.DaHangHaiRedis2, err error) {
var (
conn = d.redis.Get(ctx)
args = redis.Args{}
cacheResult [][]byte
)
defer conn.Close()
for _, uid := range mids {
args = args.Add(guardAnchorUIDKey(uid))
}
if cacheResult, err = redis.ByteSlices(conn.Do("MGET", args...)); err != nil {
if err == redis.ErrNil {
err = nil
} else {
PromError(_promGetErr)
log.Error(_errorRedisLogPrefix+"|conn.MGET(%v) error(%v)", args, err)
err = errors.Wrapf(err, "redis.StringMap(conn.Do(MGET,%v)", args)
}
return
}
dhhList = make([]*dahanghaiModel.DaHangHaiRedis2, 0)
dhhListSingle := &dahanghaiModel.DaHangHaiRedis2{}
if len(cacheResult) > 0 {
for k, v := range cacheResult {
if v == nil {
return nil, nil
}
if len(v) > 0 {
if err = json.Unmarshal([]byte(v), &dhhList); err != nil {
if err = json.Unmarshal([]byte(v), &dhhListSingle); err != nil {
log.Error("[dao.dahanghai.cache|GetDHHFromRedis] json.Unmarshal rawInfo error(%v), uid(%d), reply(%s)",
err, k, v)
return nil, nil
}
dhhList = append(dhhList, dhhListSingle)
}
}
}
}
PromInfo(_promGetSuccess)
return
}
func (d *GuardDao) delDHHFromRedis(ctx context.Context, key string) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
_, err = conn.Do("DEL", key)
if err == gmc.ErrNotFound {
err = nil
} else {
log.Error(_errorRedisLogPrefix+"|Delete(%s) error(%v)", key, err)
PromError(_promDelErr)
}
PromInfo(_promDelSuccess)
conn.Close()
return
}
func (d *GuardDao) setDHHListCache(ctx context.Context, dhhList []dahanghaiModel.DaHangHaiRedis2, uid int64) (err error) {
expire := d.getExpire()
rand.Seed(time.Now().UnixNano())
expire = expire + rand.Int31n(60)
var (
argsMid = redis.Args{}
conn = d.redis.Get(ctx)
dhhJSON []byte
)
defer conn.Close()
key := dahanghaiUIDKey(uid)
if len(dhhList) == 0 {
argsMid = argsMid.Add(key).Add("")
} else {
dhhJSON, err = json.Marshal(dhhList)
if err != nil {
log.Error("[dao.dahanghai.cache|GetDHHFromRedis] json.Marshal rawInfo error(%v), uid(%d)", err, uid)
return
}
argsMid = argsMid.Add(key).Add(string(dhhJSON))
}
if err = conn.Send("SET", argsMid...); err != nil {
err = errors.Wrap(err, "conn.Send(SET) error")
return
}
rand.Seed(time.Now().UnixNano())
expire = expire + rand.Int31n(60)
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("setDHHListCache conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
return
}
func (d *GuardDao) setAnchorGuardListCache(ctx context.Context, dhhList []dahanghaiModel.DaHangHaiRedis2, uid int64) (err error) {
expire := d.getExpire()
rand.Seed(time.Now().UnixNano())
expire = expire + rand.Int31n(60)
var (
argsMid = redis.Args{}
conn = d.redis.Get(ctx)
dhhJSON []byte
)
defer conn.Close()
key := guardAnchorUIDKey(uid)
if len(dhhList) == 0 {
argsMid = argsMid.Add(key).Add("")
} else {
dhhJSON, err = json.Marshal(dhhList)
if err != nil {
log.Error("[dao.dahanghai.cache|setAnchorGuardListCache] json.Marshal rawInfo error(%v), uid(%d)", err, uid)
return
}
argsMid = argsMid.Add(key).Add(string(dhhJSON))
}
if err = conn.Send("SET", argsMid...); err != nil {
err = errors.Wrap(err, "conn.Send(SET) error")
return
}
rand.Seed(time.Now().UnixNano())
expire = expire + rand.Int31n(60)
if err = conn.Send("EXPIRE", key, expire); err != nil {
log.Error("setAnchorGuardListCache conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
return
}
return
}
func (d *GuardDao) getAnchorRecentTopGuardCache(ctx context.Context, uid int64) (resp map[int64]int64, err error) {
resp = make(map[int64]int64)
nowTime := time.Now().Unix()
cacheKey := recentGuardTopKey(uid)
var (
conn = d.redis.Get(ctx)
)
values, err := redis.Values(conn.Do("ZRANGEBYSCORE", cacheKey, nowTime, "INF", "WITHSCORES"))
if err != nil {
log.Error("getAnchorRecentTopGuardCache.conn.Do(ZRANGEBYSCORE %v) error(%v)", cacheKey, err)
return
}
if len(values) == 0 {
return
}
var aid, unix int64
for len(values) > 0 {
if values, err = redis.Scan(values, &aid, &unix); err != nil {
log.Error("getAnchorRecentTopGuardCache.redis.Scan(%v) error(%v)", values, err)
return
}
resp[aid] = unix
}
return
}