ratelimit

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package ratelimit 提供存在 PostgreSQL 里的固定窗口计数,多实例部署时共享同一份额度。

计数放在库里而不是进程内存:内存计数在 N 个实例下会把额度放大 N 倍, 登录限流也就被摊薄成了摆设。代价是每次计数多一次写库, 而需要限流的请求(登录、注册、找回密码、上传)本来就要读写数据库。

时间一律取数据库的 now():各实例的时钟可能相差几秒,窗口边界得有唯一的裁判。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Counter

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

Counter 是固定窗口计数器。窗口从某个键的第一次计数开始,到期后重新开窗。

func New

func New(db bun.IDB) *Counter

New 构造计数器。只做装配、不访问数据库。

func (*Counter) Count

func (c *Counter) Count(ctx context.Context, key string) (int, error)

Count 返回 key 当前窗口内的次数,不计数;窗口已过期或从未计数时为 0。

func (*Counter) Hit

func (c *Counter) Hit(ctx context.Context, key string, per time.Duration) (int, error)

Hit 给 key 记一次,返回当前窗口内的累计次数(含这一次)。

func (*Counter) Reset

func (c *Counter) Reset(ctx context.Context, key string) error

Reset 清掉 key 的计数。

func (*Counter) Sweep

func (c *Counter) Sweep(ctx context.Context) (int64, error)

Sweep 删除已过期的计数,返回删除条数。正确性不依赖它(过期行在读写时都被当作不存在), 它只负责不让表随攻击无限增长。

Jump to

Keyboard shortcuts

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