ratelimit

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

README

framework-ratelimit

Go framework package for ratelimit.

Installation

go get github.com/go-anyway/framework-ratelimit@v1.0.0

Usage

See documentation for usage examples.

License

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// RateLimitRequestsTotal 限流请求总数
	RateLimitRequestsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "ratelimit_requests_total",
			Help: "Total number of rate limit requests",
		},
		[]string{"rule", "dimension", "allowed"},
	)

	// RateLimitRequestsDuration 限流检查耗时
	RateLimitRequestsDuration = promauto.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "ratelimit_requests_duration_seconds",
			Help:    "Rate limit check duration in seconds",
			Buckets: prometheus.DefBuckets,
		},
		[]string{"rule", "dimension"},
	)

	// RateLimitLimitedTotal 被限流的请求数
	RateLimitLimitedTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "ratelimit_limited_total",
			Help: "Total number of rate limited requests",
		},
		[]string{"rule", "dimension"},
	)

	// RateLimitErrorsTotal 限流错误数
	RateLimitErrorsTotal = promauto.NewCounterVec(
		prometheus.CounterOpts{
			Name: "ratelimit_errors_total",
			Help: "Total number of rate limit errors",
		},
		[]string{"rule", "error_type"},
	)
)

Functions

func SaveRulesToFile

func SaveRulesToFile(filePath string, rules []*Rule) error

SaveRulesToFile 保存限流规则到文件

func ValidateConfig

func ValidateConfig(config *Config) error

ValidateConfig 验证配置

func ValidateRule

func ValidateRule(rule *Rule) error

ValidateRule 验证规则

Types

type AlgorithmType

type AlgorithmType string

AlgorithmType 限流算法类型枚举

const (
	AlgorithmTokenBucket   AlgorithmType = "token_bucket"   // 令牌桶算法
	AlgorithmLeakyBucket   AlgorithmType = "leaky_bucket"   // 漏桶算法
	AlgorithmFixedWindow   AlgorithmType = "fixed_window"   // 固定窗口算法
	AlgorithmSlidingWindow AlgorithmType = "sliding_window" // 滑动窗口算法
)

type BusinessRateLimitRule

type BusinessRateLimitRule = Rule

BusinessRateLimitRule 业务限流规则(向后兼容别名)

type Config

type Config struct {
	Enabled      bool         `yaml:"enabled" json:"enabled"`             // 是否启用限流
	DefaultRate  float64      `yaml:"default_rate" json:"default_rate"`   // 默认速率
	DefaultBurst int          `yaml:"default_burst" json:"default_burst"` // 默认突发值
	Storage      string       `yaml:"storage" json:"storage"`             // 存储类型:local 或 redis
	Redis        *RedisConfig `yaml:"redis" json:"redis"`                 // Redis配置(可选)
	Rules        []*Rule      `yaml:"rules" json:"rules"`                 // 限流规则
}

Config 限流配置(简化后的配置结构)

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置

func MergeConfig

func MergeConfig(base, override *Config) *Config

MergeConfig 合并配置

type FallbackStrategyType

type FallbackStrategyType string

FallbackStrategyType 托底策略类型枚举

const (
	StrategyReject   FallbackStrategyType = "reject"   // 直接拒绝
	StrategyQueue    FallbackStrategyType = "queue"    // 队列等待
	StrategyDegrade  FallbackStrategyType = "degrade"  // 服务降级
	StrategyRedirect FallbackStrategyType = "redirect" // 重定向
	StrategyBypass   FallbackStrategyType = "bypass"   // 绕过限流
)

type Limiter

type Limiter interface {
	// Allow 检查是否允许通过
	Allow(ctx context.Context, key string) (bool, error)
	// Wait 等待直到允许通过
	Wait(ctx context.Context, key string) error
	// Reserve 预留一个令牌
	Reserve(ctx context.Context, key string) (*Reservation, error)
}

Limiter 限流器接口

func DefaultLimiterFactory

func DefaultLimiterFactory(options *LimiterOptions) (Limiter, error)

DefaultLimiterFactory 默认限流器工厂函数

type LimiterConfig

type LimiterConfig struct {
	Enabled     bool   `yaml:"enabled" env:"RATELIMIT_ENABLED" default:"true"`
	Rate        int    `yaml:"rate" env:"RATELIMIT_RATE" default:"100"`
	Burst       int    `yaml:"burst" env:"RATELIMIT_BURST" default:"200"`
	Algorithm   string `yaml:"algorithm" env:"RATELIMIT_ALGORITHM" default:"token_bucket"`
	EnableTrace bool   `yaml:"enable_trace" env:"RATELIMIT_ENABLE_TRACE" default:"true"`
}

LimiterConfig 限流器配置结构体(用于从配置文件创建)

func (*LimiterConfig) ToLimiterOptions

func (c *LimiterConfig) ToLimiterOptions() (*LimiterOptions, error)

ToLimiterOptions 转换为 LimiterOptions

func (*LimiterConfig) Validate

func (c *LimiterConfig) Validate() error

Validate 验证限流器配置

type LimiterFactory

type LimiterFactory func(options *LimiterOptions) (Limiter, error)

LimiterFactory 限流器工厂函数类型

type LimiterOptions

type LimiterOptions struct {
	// 基础选项
	Rate       float64       `yaml:"rate" json:"rate"`               // 每秒请求数
	Burst      int           `yaml:"burst" json:"burst"`             // 突发请求数
	Algorithm  AlgorithmType `yaml:"algorithm" json:"algorithm"`     // 限流算法
	WindowSize time.Duration `yaml:"window_size" json:"window_size"` // 窗口大小(仅对窗口算法有效)

	// Redis 选项
	RedisPrefix string `yaml:"redis_prefix" json:"redis_prefix"` // Redis 键前缀

	// 追踪选项
	EnableTrace bool `yaml:"enable_trace" json:"enable_trace"` // 是否启用追踪(用于日志)

	// 性能选项
	CacheSize int `yaml:"cache_size" json:"cache_size"` // 本地缓存大小(LRU缓存)
}

LimiterOptions 限流器选项(简化后)

func DefaultLimiterOptions

func DefaultLimiterOptions() *LimiterOptions

DefaultLimiterOptions 返回默认的限流器选项

func (*LimiterOptions) Validate

func (o *LimiterOptions) Validate() error

Validate 验证限流器选项

type LocalLimiter

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

LocalLimiter 本地限流器实现(使用LRU缓存)

func NewLocalLimiter

func NewLocalLimiter(options *LimiterOptions) (*LocalLimiter, error)

NewLocalLimiter 创建新的本地限流器

func (*LocalLimiter) Allow

func (l *LocalLimiter) Allow(ctx context.Context, key string) (bool, error)

Allow 检查是否允许通过

func (*LocalLimiter) Clear

func (l *LocalLimiter) Clear()

Clear 清除所有限流器

func (*LocalLimiter) Close

func (l *LocalLimiter) Close() error

Close 关闭限流器

func (*LocalLimiter) Reserve

func (l *LocalLimiter) Reserve(ctx context.Context, key string) (*Reservation, error)

Reserve 预留一个令牌

func (*LocalLimiter) Size

func (l *LocalLimiter) Size() int

Size 返回当前限流器数量

func (*LocalLimiter) UpdateOptions

func (l *LocalLimiter) UpdateOptions(options *LimiterOptions) error

UpdateOptions 更新限流器选项

func (*LocalLimiter) Wait

func (l *LocalLimiter) Wait(ctx context.Context, key string) error

Wait 等待直到允许通过

type Manager

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

Manager 业务限流管理器实现(简化版,内联所有功能)

func LoadConfig

func LoadConfig(config *Config) (*Manager, error)

LoadConfig 加载限流配置

func NewManager

func NewManager(options *ManagerOptions) (*Manager, error)

NewManager 创建新的业务限流管理器

func (*Manager) Allow

func (m *Manager) Allow(ctx context.Context, req *http.Request) (*RateLimitResult, error)

Allow 检查请求是否允许通过

func (*Manager) Close

func (m *Manager) Close() error

Close 关闭管理器

func (*Manager) GetRules

func (m *Manager) GetRules() []*Rule

GetRules 获取所有限流规则(按优先级排序)

func (*Manager) RegisterRule

func (m *Manager) RegisterRule(rule *Rule) error

RegisterRule 注册限流规则

func (*Manager) RemoveRule

func (m *Manager) RemoveRule(name string) error

RemoveRule 移除限流规则

func (*Manager) SetUserIDExtractor

func (m *Manager) SetUserIDExtractor(extractor UserIDExtractor)

SetUserIDExtractor 设置用户ID提取器(用于解析JWT,避免循环依赖)

func (*Manager) UpdateRule

func (m *Manager) UpdateRule(name string, rule *Rule) error

UpdateRule 更新限流规则

type ManagerOptions

type ManagerOptions struct {
	// 规则选项
	DefaultRulePriority int `yaml:"default_rule_priority" json:"default_rule_priority"` // 默认规则优先级

	// 限流器选项
	DefaultLimiterOptions *LimiterOptions `yaml:"default_limiter_options" json:"default_limiter_options"` // 默认限流器选项
	LimiterFactory        LimiterFactory  `yaml:"-" json:"-"`                                             // 限流器工厂函数

	// 键前缀(用于生成限流键)
	KeyPrefix string `yaml:"key_prefix" json:"key_prefix"` // 键前缀
}

ManagerOptions 限流管理器选项(简化后)

func DefaultManagerOptions

func DefaultManagerOptions() *ManagerOptions

DefaultManagerOptions 返回默认的限流管理器选项

func (*ManagerOptions) Validate

func (o *ManagerOptions) Validate() error

Validate 验证管理器选项

type MatchCondition

type MatchCondition struct {
	ID       string        `yaml:"id" json:"id"`             // 条件ID
	Field    MatchField    `yaml:"field" json:"field"`       // 匹配字段
	Operator MatchOperator `yaml:"operator" json:"operator"` // 匹配操作符
	Value    string        `yaml:"value" json:"value"`       // 匹配值
	Negate   bool          `yaml:"negate" json:"negate"`     // 是否取反
}

MatchCondition 匹配条件

type MatchField

type MatchField string

MatchField 匹配字段枚举

const (
	FieldPath        MatchField = "path"         // 请求路径
	FieldMethod      MatchField = "method"       // HTTP方法
	FieldHeader      MatchField = "header"       // 请求头
	FieldQuery       MatchField = "query"        // 查询参数
	FieldCookie      MatchField = "cookie"       // Cookie
	FieldIP          MatchField = "ip"           // IP地址
	FieldUserAgent   MatchField = "user_agent"   // User-Agent
	FieldContentType MatchField = "content_type" // Content-Type
	FieldBody        MatchField = "body"         // 请求体
	FieldCustom      MatchField = "custom"       // 自定义字段
)

type MatchOperator

type MatchOperator string

MatchOperator 匹配操作符枚举

const (
	OperatorEquals    MatchOperator = "equals"     // 等于
	OperatorContains  MatchOperator = "contains"   // 包含
	OperatorPrefix    MatchOperator = "prefix"     // 前缀匹配
	OperatorSuffix    MatchOperator = "suffix"     // 后缀匹配
	OperatorRegex     MatchOperator = "regex"      // 正则匹配
	OperatorExists    MatchOperator = "exists"     // 存在
	OperatorNotExists MatchOperator = "not_exists" // 不存在
	OperatorIn        MatchOperator = "in"         // 在列表中
	OperatorNotIn     MatchOperator = "not_in"     // 不在列表中
	OperatorGreater   MatchOperator = "greater"    // 大于
	OperatorLess      MatchOperator = "less"       // 小于
	OperatorBetween   MatchOperator = "between"    // 在范围内
)

type RateLimitConfig

type RateLimitConfig = Config

RateLimitConfig 限流配置(向后兼容别名)

type RateLimitDimension

type RateLimitDimension string

RateLimitDimension 限流维度枚举

const (
	DimensionGlobal    RateLimitDimension = "global"     // 全局限流
	DimensionIP        RateLimitDimension = "ip"         // IP地址限流
	DimensionUser      RateLimitDimension = "user"       // 用户ID限流
	DimensionAPI       RateLimitDimension = "api"        // API路径限流
	DimensionMethod    RateLimitDimension = "method"     // HTTP方法限流
	DimensionUserAgent RateLimitDimension = "user_agent" // User-Agent限流
	DimensionRegion    RateLimitDimension = "region"     // 地域限流
	DimensionCustom    RateLimitDimension = "custom"     // 自定义维度
)

type RateLimitManager

type RateLimitManager interface {
	// Allow 检查请求是否允许通过
	Allow(ctx context.Context, req *http.Request) (*RateLimitResult, error)

	// RegisterRule 注册限流规则
	RegisterRule(rule *Rule) error

	// UpdateRule 更新限流规则
	UpdateRule(name string, rule *Rule) error

	// RemoveRule 移除限流规则
	RemoveRule(name string) error

	// GetRules 获取所有限流规则
	GetRules() []*Rule
}

RateLimitManager 限流管理器接口

type RateLimitResult

type RateLimitResult struct {
	Allowed     bool                   `json:"allowed"`      // 是否允许通过
	RuleName    string                 `json:"rule_name"`    // 匹配的规则名称
	Dimension   RateLimitDimension     `json:"dimension"`    // 触发限流的维度
	Reason      string                 `json:"reason"`       // 限流原因
	Strategy    FallbackStrategyType   `json:"strategy"`     // 托底策略类型
	WaitTime    time.Duration          `json:"wait_time"`    // 等待时间(仅对queue类型有效)
	RedirectURL string                 `json:"redirect_url"` // 重定向URL(仅对redirect类型有效)
	Degraded    bool                   `json:"degraded"`     // 是否降级处理
	Metadata    map[string]interface{} `json:"metadata"`     // 元数据
}

RateLimitResult 限流结果

type RedisClient

type RedisClient interface {
	Eval(ctx context.Context, script string, keys []string, args ...interface{}) (interface{}, error)
}

RedisClient Redis 客户端接口

type RedisConfig

type RedisConfig struct {
	Address  string `yaml:"address" json:"address"`   // Redis地址
	Password string `yaml:"password" json:"password"` // Redis密码
	DB       int    `yaml:"db" json:"db"`             // Redis数据库
	Prefix   string `yaml:"prefix" json:"prefix"`     // 键前缀
}

RedisConfig Redis配置

type RedisLimiter

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

RedisLimiter Redis 分布式限流器实现

func NewRedisLimiter

func NewRedisLimiter(client RedisClient, options *LimiterOptions) (*RedisLimiter, error)

NewRedisLimiter 创建新的 Redis 限流器

func (*RedisLimiter) Allow

func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, error)

Allow 检查是否允许通过

func (*RedisLimiter) Close

func (l *RedisLimiter) Close() error

Close 关闭限流器

func (*RedisLimiter) GetClient

func (l *RedisLimiter) GetClient() RedisClient

GetClient 获取 Redis 客户端

func (*RedisLimiter) Reserve

func (l *RedisLimiter) Reserve(ctx context.Context, key string) (*Reservation, error)

Reserve 预留一个令牌

func (*RedisLimiter) SetClient

func (l *RedisLimiter) SetClient(client RedisClient)

SetClient 设置 Redis 客户端

func (*RedisLimiter) UpdateOptions

func (l *RedisLimiter) UpdateOptions(options *LimiterOptions) error

UpdateOptions 更新限流器选项

func (*RedisLimiter) Wait

func (l *RedisLimiter) Wait(ctx context.Context, key string) error

Wait 等待直到允许通过

type Reservation

type Reservation struct {
	OK     bool
	Delay  time.Duration
	Tokens int
}

Reservation 预留信息

type Rule

type Rule struct {
	Name        string               `yaml:"name" json:"name"`               // 规则名称
	Enabled     bool                 `yaml:"enabled" json:"enabled"`         // 是否启用
	Priority    int                  `yaml:"priority" json:"priority"`       // 优先级(数字越小优先级越高)
	Dimensions  []RateLimitDimension `yaml:"dimensions" json:"dimensions"`   // 限流维度
	Conditions  []*MatchCondition    `yaml:"conditions" json:"conditions"`   // 匹配条件
	Rate        float64              `yaml:"rate" json:"rate"`               // 每秒请求数
	Burst       int                  `yaml:"burst" json:"burst"`             // 突发请求数
	Algorithm   AlgorithmType        `yaml:"algorithm" json:"algorithm"`     // 限流算法
	Fallback    FallbackStrategyType `yaml:"fallback" json:"fallback"`       // 托底策略类型(简化)
	Description string               `yaml:"description" json:"description"` // 规则描述
	CreatedAt   time.Time            `yaml:"created_at" json:"created_at"`   // 创建时间
	UpdatedAt   time.Time            `yaml:"updated_at" json:"updated_at"`   // 更新时间
}

Rule 限流规则(简化后的规则结构)

func LoadRulesFromConfigDir

func LoadRulesFromConfigDir(configDir string) ([]*Rule, error)

LoadRulesFromConfigDir 从配置目录加载限流规则

func LoadRulesFromFile

func LoadRulesFromFile(filePath string) ([]*Rule, error)

LoadRulesFromFile 从文件加载限流规则

type RuleConfigFile

type RuleConfigFile struct {
	Rules []*Rule `yaml:"rules" json:"rules"`
}

RuleConfigFile 限流规则配置文件结构

type UserIDExtractor

type UserIDExtractor interface {
	ExtractUserID(req *http.Request) string
}

UserIDExtractor 用户ID提取器接口(用于避免循环依赖)

Jump to

Keyboard shortcuts

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