leaderboard

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package leaderboard 提供排行榜的内存排名缓存:用堆排序维护每个榜的有序结构, O(log N) 查"我的名次"、按名次取记录,避免高频读时每次 ORDER BY 击穿数据库。

设计要点:

  • 每个榜 + 过期周期维护一个独立的 RankCache;
  • Fill 全量加载、Insert/Delete 增量维护、Get 按主人查名次;
  • 黑名单机制:某些超大或写频繁的榜可不进缓存,退化为不缓存(本包表现为 Get 返回 -1)。

适用场景:游戏排行榜、积分榜、热榜的"我的排名/TopN"高频读。

零值不可用,用 New 构造。RankCache 并发安全。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RankCache

type RankCache struct {
	// contains filtered or unexported fields
}

RankCache 管理多个排行榜的内存排名缓存。

func New

func New(blacklist ...string) *RankCache

New 创建 RankCache。blacklist 为不缓存的榜 ID 列表;含 "*" 表示全部不缓存。

func (*RankCache) Around

func (r *RankCache) Around(leaderboardID string, expiry int64, ownerID string, around int) []Record

Around 返回某 owner 前后各 range 条记录(含自己)。

func (*RankCache) Delete

func (r *RankCache) Delete(leaderboardID string, expiry int64, ownerID string) bool

Delete 删除一条记录。返回是否曾存在。

func (*RankCache) DeleteLeaderboard

func (r *RankCache) DeleteLeaderboard(leaderboardID string, expiry int64) bool

DeleteLeaderboard 移除整个榜的缓存(过期/重置时调用)。

func (*RankCache) Fill

func (r *RankCache) Fill(leaderboardID string, expiry int64, order SortOrder, records []Record, enable bool) int

Fill 全量加载一个榜的记录,构建缓存。返回缓存的记录数。 若该榜在黑名单中,返回 0 且不缓存。 enable=false 时也跳过(用于运行时动态关闭某榜缓存)。

func (*RankCache) Get

func (r *RankCache) Get(leaderboardID string, expiry int64, ownerID string) int64

Get 返回某 owner 的名次(从 1 起)。未缓存或不存在返回 -1。

func (*RankCache) GetByRank

func (r *RankCache) GetByRank(leaderboardID string, expiry int64, rank int) (Record, bool)

GetByRank 返回第 rank 名(从 1 起)的记录。rank 越界返回零值 + false。

func (*RankCache) Insert

func (r *RankCache) Insert(leaderboardID string, expiry int64, order SortOrder, rec Record, enable bool) int64

Insert 插入或更新一条记录,增量维护堆。返回该 owner 的当前名次(从 1 起)。 若该榜未缓存,返回 -1。

func (*RankCache) Size

func (r *RankCache) Size(leaderboardID string, expiry int64) int

Size 返回某榜的缓存记录数。

func (*RankCache) TopN

func (r *RankCache) TopN(leaderboardID string, expiry int64, n int) []Record

TopN 返回前 N 名(按 order)。N 超过总数时返回全部。

type Record

type Record struct {
	OwnerID  string
	Score    int64
	Subscore int64 // 次级分数,Score 相同时按此排序
}

Record 是一条榜记录。

type SortOrder

type SortOrder int

SortOrder 排序方向。

const (
	SortAscending  SortOrder = iota // 升序:分数小者居前(如用时少的赢家)
	SortDescending                  // 降序:分数大者居前(如积分)
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL