package yeartop import ( "91porn-server/common/log" "91porn-server/common/redis" services "91porn-server/common/top" "fmt" "time" ) // getCacheKeys 获取需要操作的key func getCacheKeys(tp services.TopName) []string { y := time.Now().Year() var keys []string var i int for i = 0; i < 2; i++ { keys = append(keys, fmt.Sprintf("year_top_%s_%d", tp, y-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) 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) 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 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 }