Files
huangguo_server/common/top/dailytop/grow.go
T
rootandClaude Opus 5 8679200f41 Initial commit
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 13:57:10 +08:00

114 lines
2.5 KiB
Go

package dailytop
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 < 2; i++ {
keys = append(keys, fmt.Sprintf("daliy_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*3)
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*3)
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)
k := len(keys) - 2 // 获取倒数第二个,也就是前一天
if k < 0 {
return []string{}, map[string]int64{}, false
}
key := keys[k]
hasNext := false
count, err := redis.Handler.ZCard(key)
if err != nil {
return nil, nil, false
}
if skip >= count {
return nil, nil, false
}
if count > skip+size {
hasNext = true
}
srt, topVal := redis.Handler.ZRevRangeWithScores2(key, skip, size)
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, hasNext
}