ratelimit

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package ratelimit 提供基于 Redis 有序集合的滑动窗口限流,并内置本地内存降级。

核心算法与业务解耦:限流 key 由调用方自行构造,Redis 客户端由调用方注入。 当 Redis 不可用或执行失败时自动降级到本地内存限流(多实例不共享计数)。

使用方式:

limiter := ratelimit.NewLimiter(redisClient)
defer limiter.Close()
if !limiter.Allow(ctx, "api:create", 10, 60) {
    // 触发限流
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

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

Limiter 限流器。由调用方持有实例,并通过 Close 方法释放后台资源。

func NewLimiter

func NewLimiter(client redis.UniversalClient) *Limiter

NewLimiter 创建一个新的限流器实例。

参数:

  • client: Redis 客户端;传 nil 时全部降级到本地内存限流。

返回值:

  • *Limiter: 限流器实例,使用完毕后需调用 Close 释放资源。

func (*Limiter) Allow

func (l *Limiter) Allow(ctx context.Context, key string, maxRequests int, windowSeconds int) bool

Allow 基于 Redis 有序集合的滑动窗口限流。 client 为 nil 或执行失败时自动降级到本地内存限流。

参数:

  • ctx: 请求上下文
  • key: 限流 key(业务限流 key 由调用方自行构造)
  • maxRequests: 窗口内最大请求数
  • windowSeconds: 窗口长度(秒)

返回值:

  • bool: true 表示允许通过,false 表示触发限流

func (*Limiter) AllowLocal

func (l *Limiter) AllowLocal(key string, maxRequests, windowSeconds int) bool

AllowLocal 本地内存滑动窗口限流(多实例不共享计数)。

参数:

  • key: 限流 key
  • maxRequests: 窗口内最大请求数
  • windowSeconds: 窗口长度(秒)

返回值:

  • bool: true 表示允许通过,false 表示触发限流

func (*Limiter) Close

func (l *Limiter) Close()

Close 释放限流器占用的资源,包括停止本地降级限流器的后台清理协程。 多次调用安全。

Jump to

Keyboard shortcuts

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