103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package weektop
|
|
|
|
import (
|
|
"91porn-server/common/log"
|
|
"91porn-server/common/redis"
|
|
services "91porn-server/common/top"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// getCacheKeys 获取需要操作的key
|
|
func getCacheKeys(tp services.TopName) []string {
|
|
t := time.Now().Unix()
|
|
d := t / 86400
|
|
var keys []string
|
|
var i int64
|
|
for i = 0; i < 7; i++ {
|
|
keys = append(keys, fmt.Sprintf("week_top_%s_%d", tp, d-i))
|
|
}
|
|
|
|
return keys
|
|
}
|
|
|
|
// Incr 增加
|
|
func Incr(tp services.TopName, id string, count float64) {
|
|
keys := getCacheKeys(tp)
|
|
for _, key := range keys {
|
|
if !redis.Handler.Exists(key) {
|
|
_, _ = redis.Handler.ZIncrBy(key, count, id)
|
|
_, _ = redis.Handler.ExpireKey(key, time.Hour*24*8)
|
|
continue
|
|
}
|
|
_, _ = redis.Handler.ZIncrBy(key, count, id)
|
|
}
|
|
}
|
|
|
|
// Decr 减少
|
|
func Decr(tp services.TopName, id string, count float64) {
|
|
keys := getCacheKeys(tp)
|
|
for _, key := range keys {
|
|
if !redis.Handler.Exists(key) {
|
|
_, _ = redis.Handler.ZIncrBy(key, -count, id)
|
|
_, _ = redis.Handler.ExpireKey(key, time.Hour*24*8)
|
|
continue
|
|
}
|
|
_, _ = redis.Handler.ZIncrBy(key, -count, id)
|
|
}
|
|
}
|
|
|
|
// Remove 移除
|
|
func Remove(tp services.TopName, id string) {
|
|
keys := getCacheKeys(tp)
|
|
for _, key := range keys {
|
|
log.Info("Remove key", log.Any("key", key), log.Any("id", id))
|
|
redis.Handler.ZRem(key, id)
|
|
}
|
|
}
|
|
|
|
// GetTop 获取排行榜头部
|
|
func GetTop(tp services.TopName, count int64) ([]string, map[string]int64) {
|
|
keys := getCacheKeys(tp)
|
|
key := keys[len(keys)-1]
|
|
srt, topVal := redis.Handler.ZRevRangeWithScores2(key, 0, count)
|
|
var ids []string
|
|
scores := make(map[string]int64)
|
|
for _, id := range srt {
|
|
score, ok := topVal[id]
|
|
if !ok {
|
|
continue
|
|
}
|
|
|
|
ids = append(ids, id)
|
|
scores[id] = int64(score)
|
|
}
|
|
|
|
return ids, scores
|
|
}
|
|
|
|
// GetTopByPage 获取排行榜头部
|
|
func GetTopByPage(tp services.TopName, skip, size int64) ([]string, map[string]int64, bool) {
|
|
keys := getCacheKeys(tp)
|
|
key := keys[len(keys)-1]
|
|
hasNext := false
|
|
srt, topVal := redis.Handler.ZRevRangeWithScores2(key, skip, size+1)
|
|
var ids []string
|
|
if len(srt) > int(size) {
|
|
hasNext = true
|
|
srt = srt[:size]
|
|
}
|
|
scores := make(map[string]int64)
|
|
for _, id := range srt {
|
|
score, ok := topVal[id]
|
|
if !ok {
|
|
continue
|
|
}
|
|
|
|
ids = append(ids, id)
|
|
scores[id] = int64(score)
|
|
}
|
|
|
|
return ids, scores, hasNext
|
|
}
|