svip_vip_noble.go 2.5 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
package user_c

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"sync"
	"time"
)

type UserLevel struct {
	UserId mysql.ID
	Level  int
}

var svipVipNobleLock sync.RWMutex

var svipLevel = make(map[mysql.ID]int)     // userId->svipLevel
var nobleLevel = make(map[mysql.ID]uint16) // userId->nobleLevel
var userVips = make(map[mysql.ID]bool)     // userId->isVip

// 加载数据到lru
func LoadAllSvipVipNoble(model *domain.Model) {
	start := time.Now()
	var svips []UserLevel
	svipMap := make(map[mysql.ID]int)
	if err := model.DB().Table("user_svip").Select("user_id,level").Where("level > 0").Find(&svips).Error; err != nil {
		model.Log.Errorf("LoadAllSvip fail:%v", err)
	} else {
		for _, v := range svips {
			svipMap[v.UserId] = v.Level
		}
	}
	var nobles []UserLevel
	nobleMap := make(map[mysql.ID]uint16)
	if err := model.DB().Table("user_noble").Select("user_id,MAX(level) level").
hujiebin's avatar
hujiebin committed
36
		Where("level > 0 AND end_time > ?", time.Now()).Group("user_id").Find(&nobles).Error; err != nil {
hujiebin's avatar
hujiebin committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
		model.Log.Errorf("LoadAllNoble fail:%v", err)
	} else {
		for _, v := range nobles {
			nobleMap[v.UserId] = uint16(v.Level)
		}
	}

	var vips []UserLevel
	vipMap := make(map[mysql.ID]bool)
	if err := model.DB().Table("user_vip").Select("user_id").
		Where("expire_at > ?", time.Now()).Find(&vips).Error; err != nil {
		model.Log.Errorf("LoadAllVip fail:%v", err)
	} else {
		for _, v := range vips {
			vipMap[v.UserId] = true
		}
	}

	// 上锁赋值
	svipVipNobleLock.Lock()
	svipLevel = svipMap
	nobleLevel = nobleMap
	userVips = vipMap
	svipVipNobleLock.Unlock()
	model.Log.Infof("LoadAllSvipVipNoble svip:%v,vip:%v,noble:%v,cost:%vs", len(svipMap), len(vipMap), len(nobleMap), time.Now().Sub(start).Seconds())
}

func BatchGetNobleLevel(model *domain.Model, userIds []uint64) map[uint64]uint16 {
	res := make(map[uint64]uint16)
	svipVipNobleLock.RLock()
	defer svipVipNobleLock.RUnlock()
	for _, userId := range userIds {
		res[userId] = nobleLevel[userId]
	}
	return res
}

func MGetUserSvipLevel(model *domain.Model, userIds []uint64) map[uint64]int {
	res := make(map[uint64]int)
	svipVipNobleLock.RLock()
	defer svipVipNobleLock.RUnlock()
	for _, userId := range userIds {
		res[userId] = svipLevel[userId]
	}
	return res
}

func BatchGetVips(model *domain.Model, userIds []uint64) map[uint64]*int64 {
	res := make(map[uint64]*int64)
	svipVipNobleLock.RLock()
	defer svipVipNobleLock.RUnlock()
	for _, userId := range userIds {
		vip := int64(1)
		if userVips[userId] {
			res[userId] = &vip
		}
	}
	return res
}