svip_vip_noble.go 2.32 KB
Newer Older
iamhujiebin's avatar
iamhujiebin 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 36 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
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) {
	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").
		Where("level > 0 AND end_time > ?", time.Now()).Find(&nobles).Error; err != nil {
		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
	defer svipVipNobleLock.Unlock()
}

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
}