46 lines
1.3 KiB
Go
Raw Normal View History

2025-01-24 18:36:46 +08:00
package rankings
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
// Ranking 排行榜结构体
type Ranking struct {
c *redis.Client
}
const EcpmRankingsListPrefix = "ecpm:rankings:"
// NewRanking 创建一个新的排行榜实例
func NewRanking(c *redis.Client) *Ranking {
return &Ranking{
c: c,
}
}
2025-01-25 18:05:37 +08:00
func GetRankingsCacheKey(appId uint32, t uint32) string {
2025-01-24 18:36:46 +08:00
return fmt.Sprintf("%sappId:%d:type:%d", EcpmRankingsListPrefix, appId, t)
}
// SetList 向排行榜中添加成员及其分数
func (r *Ranking) SetList(ctx context.Context, key string, data ...redis.Z) {
r.c.ZAdd(ctx, key, data...)
2025-01-24 18:36:46 +08:00
}
// GetList 获取排行榜,按照分数从高到低排序
func (r *Ranking) GetList(ctx context.Context, key string, start, stop int64) (data []redis.Z, err error) {
return r.c.ZRevRangeWithScores(ctx, key, start, stop).Result()
2025-01-24 18:36:46 +08:00
}
// GetRank 获取指定成员在排行榜中的排名(排名从 0 开始,分数越高排名越靠前)
func (r *Ranking) GetRank(ctx context.Context, key, member string) (rank int64, err error) {
return r.c.ZRevRank(ctx, key, member).Result()
2025-01-24 18:36:46 +08:00
}
// GetScore 获取指定成员在排行榜中的分数
func (r *Ranking) GetScore(ctx context.Context, key, member string) (score float64, err error) {
return r.c.ZScore(ctx, key, member).Result()
2025-01-24 18:36:46 +08:00
}