limiter

package
v0.0.0-...-fb81f76 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2026 License: MIT Imports: 14 Imported by: 0

README

Limiter - 限流器组件

高性能、可扩展的限流器组件,支持多种限流算法和存储方式。

特性

  • 多种限流算法

    • 令牌桶(Token Bucket):支持突发流量
    • 滑动窗口(Sliding Window):精确QPS控制
    • 并发限流(Concurrency):控制并发数
    • 自适应限流(Adaptive):根据系统负载动态调整
  • 多种存储方式

    • 内存存储:单机高性能
    • Redis存储:分布式共享(支持单机和集群)
  • 事件驱动

    • 可订阅限流事件(允许/拒绝/等待)
    • 实时指标采集
    • 支持自定义监听器
  • 可选启用

    • 配置驱动的限流策略
    • 未配置的资源自动放行
    • 优雅降级
  • 依赖注入

    • Logger注入
    • AdaptiveProvider可选注入

快速开始

基本使用
package main

import (
    "context"
    "github.com/KOMKZ/go-yogan/limiter"
    "github.com/KOMKZ/go-yogan/logger"
)

func main() {
    // 1. 创建配置
    cfg := limiter.Config{
        Enabled:   true,
        StoreType: "memory",
        Default: limiter.ResourceConfig{
            Algorithm: "token_bucket",
            Rate:      100,  // 100 QPS
            Capacity:  200,  // 允许200突发
        },
    }
    
    // 2. 创建限流器
    log := logger.NewCtxZapLogger("app")
    lim, _ := limiter.NewManagerWithLogger(cfg, log, nil)
    defer lim.Close()
    
    // 3. 使用限流器
    ctx := context.Background()
    allowed, _ := lim.Allow(ctx, "api:/users")
    
    if !allowed {
        // 请求被限流
        return
    }
    
    // 处理请求
}
Gin中间件集成(推荐方式)

设计理念

  • 中间件全局应用:作用于所有接口
  • 配置驱动限流:只对配置了的资源进行限流
  • 未配置自动放行:未在 limiter.resources 中配置的接口不受限流影响
import (
    "github.com/KOMKZ/go-yogan/limiter"
    "github.com/KOMKZ/go-yogan/middleware"
    "github.com/gin-gonic/gin"
)

func main() {
    // 1. 创建限流器,配置需要限流的资源
    cfg := limiter.Config{
        Enabled:   true,
        StoreType: "memory",
        Resources: map[string]limiter.ResourceConfig{
            // 只对这些资源进行限流
            "POST:/api/users": {
                Algorithm: "token_bucket",
                Rate:      10,   // 10 req/s
                Capacity:  20,
            },
            "GET:/limiter-test": {
                Algorithm: "token_bucket",
                Rate:      5,
                Capacity:  10,
            },
        },
    }
    
    log := logger.NewCtxZapLogger("app")
    manager, _ := limiter.NewManagerWithLogger(cfg, log, nil)
    
    // 2. 创建Gin应用
    router := gin.Default()
    
    // 3. 全局应用限流中间件(推荐)
    //    - 中间件作用于所有接口
    //    - 但只对在 Resources 中配置的资源进行限流
    //    - 未配置的资源会自动放行
    rateLimiterCfg := middleware.DefaultRateLimiterConfig(manager)
    rateLimiterCfg.KeyFunc = middleware.RateLimiterKeyByPath  // 按路径限流
    rateLimiterCfg.SkipPaths = []string{"/", "/health"}       // 白名单(跳过中间件)
    
    router.Use(middleware.RateLimiterWithConfig(rateLimiterCfg))
    
    // 4. 注册路由
    router.POST("/api/users", createUser)      // ✅ 会被限流(已配置)
    router.GET("/api/users", getUsers)         // ✅ 不会被限流(未配置,自动放行)
    router.GET("/limiter-test", limiterTest)   // ✅ 会被限流(已配置)
    router.GET("/", index)                     // ✅ 不会被限流(在白名单中)
    
    router.Run(":8080")
}

// 其他键函数示例
// rateLimiterCfg.KeyFunc = middleware.RateLimiterKeyByIP           // 按IP限流
// rateLimiterCfg.KeyFunc = middleware.RateLimiterKeyByUser         // 按用户限流
// rateLimiterCfg.KeyFunc = middleware.RateLimiterKeyByPathAndIP    // 按路径+IP限流
// rateLimiterCfg.KeyFunc = middleware.RateLimiterKeyByAPIKey       // 按API Key限流

// - middleware.RateLimiterKeyByAPIKey // 按API Key限流


### 配置示例

```yaml
limiter:
  enabled: true
  store_type: memory
  event_bus_buffer: 500
  
  # 默认配置
  default:
    algorithm: token_bucket
    rate: 100
    capacity: 200
  
  # 资源级配置
  resources:
    # 令牌桶
    "POST:/api/users":
      algorithm: token_bucket
      rate: 50
      capacity: 100
    
    # 滑动窗口
    "GET:/api/orders":
      algorithm: sliding_window
      limit: 1000
      window_size: 1s
    
    # 并发限流
    "db:query":
      algorithm: concurrency
      max_concurrency: 50
    
    # 自适应限流
    "grpc:OrderService":
      algorithm: adaptive
      min_limit: 100
      max_limit: 1000
      target_cpu: 0.7

测试

cd src/yogan/limiter
go test -v -cover

测试覆盖率

当前覆盖率:82.6%

已完成核心功能测试:

  • ✅ 令牌桶算法(完整测试)
  • ✅ 滑动窗口算法(完整测试)
  • ✅ 并发限流算法(完整测试)
  • ✅ 自适应限流算法(完整测试)
  • ✅ 内存存储(完整测试)
  • Redis存储(完整测试,使用 miniredis)
  • ✅ 配置管理(完整测试)
  • ✅ 限流器Manager(完整测试)
  • ✅ 事件系统(完整测试)

架构设计

参考:articles/132-rate-limiter-architecture-design.md

核心组件
├── limiter.go              # 核心接口
├── limiter_impl.go         # Manager实现
├── algorithm.go            # 算法接口
├── algo_token_bucket.go    # 令牌桶算法
├── algo_sliding_window.go  # 滑动窗口算法
├── algo_concurrency.go     # 并发限流算法
├── algo_adaptive.go        # 自适应限流算法
├── store.go                # 存储接口
├── store_memory.go         # 内存存储
├── config.go               # 配置管理
├── event.go                # 事件定义
├── event_bus.go            # 事件总线
├── metrics.go              # 指标采集
└── errors.go               # 错误定义
设计原则
  • SOLID: 单一职责、开闭原则、里氏替换、接口隔离、依赖倒置
  • DRY: 公共逻辑提取复用
  • KISS: API简洁直观
  • YAGNI: 不过度设计
策略模式
  • 算法可插拔(Token Bucket/Sliding Window/Concurrency/Adaptive)
  • 存储可切换(Memory/Redis)
  • 事件驱动(可观测、可扩展)

TODO

  • 提升测试覆盖率到95%+
  • Gin中间件(已完成,已迁移到 middleware 包)
  • gRPC拦截器
  • 集成到Governance组件

License

MIT

Documentation

Overview

Package limiter provides rate limiting functionality

Design philosophy: - Standalone package, depends only on the logger component of yogan - Event-driven, the application layer can subscribe to all events - Metrics exposed, application layer can access real-time data - Optional enablement, does not take effect if not configured - Supports multiple algorithms: token bucket, sliding window, concurrent rate limiting, adaptive - Support multiple storages: memory, Redis

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLimitExceeded Exceeds rate limiting threshold
	ErrLimitExceeded = errors.New("rate limit exceeded")

	// ErrWaitTimeout timeout waiting
	ErrWaitTimeout = errors.New("wait timeout")

	// ErrKeyNotFound Key does not exist
	ErrKeyNotFound = errors.New("key not found")

	// ErrInvalidConfig Invalid configuration
	ErrInvalidConfig = errors.New("invalid config")

	// ErrStoreNotSupported Storage Not Supported
	ErrStoreNotSupported = errors.New("store operation not supported")

	// ErrResourceNotFound Resource not found
	ErrResourceNotFound = errors.New("resource not found")
)

Functions

This section is empty.

Types

type AdaptiveProvider

type AdaptiveProvider interface {
	// GetCPUUsage Gets CPU usage (0.0-1.0)
	GetCPUUsage() float64

	// GetMemoryUsage Gets memory usage (0.0-1.0)
	GetMemoryUsage() float64

	// GetSystemLoad Obtain system load (usually load average per CPU core)
	GetSystemLoad() float64
}

AdaptiveProvider adaptive rate limiting data provider (dependency injection)

Usage instructions: - Implement this interface to provide system load data (CPU, memory, system load) - If Provider is not injected, adaptive rate limiting will not be effective, falling back to fixed rate limiting - Specific collection logic can be implemented using libraries such as gopsutil

Example implementation:

type SystemMetricsProvider struct {

// Can integrate libraries like gopsutil

}

func (p *SystemMetricsProvider) GetCPUUsage() float64 {

// Implement CPU usage collection

    return 0.65
}

type Algorithm

type Algorithm interface {
	// Allow check if the request is permitted
	Allow(ctx context.Context, store Store, resource string, n int64, cfg ResourceConfig) (*Response, error)

	// Wait for permission (blocking until acquired or timed out)
	Wait(ctx context.Context, store Store, resource string, n int64, cfg ResourceConfig, timeout time.Duration) error

	// GetMetrics retrieves current metrics
	GetMetrics(ctx context.Context, store Store, resource string) (*AlgorithmMetrics, error)

	// Reset reset status
	Reset(ctx context.Context, store Store, resource string) error

	// Name Returns algorithm name
	Name() string
}

Rate limiting algorithm interface (strategy pattern)

func GetAlgorithm

func GetAlgorithm(cfg ResourceConfig, provider AdaptiveProvider) Algorithm

GetAlgorithm obtains an algorithm instance according to the configuration

func NewAdaptiveAlgorithm

func NewAdaptiveAlgorithm(provider AdaptiveProvider) Algorithm

Create new adaptive rate limiting algorithm

func NewConcurrencyAlgorithm

func NewConcurrencyAlgorithm() Algorithm

NewConcurrencyAlgorithm creates concurrency rate limiting algorithm

func NewSlidingWindowAlgorithm

func NewSlidingWindowAlgorithm() Algorithm

Create new sliding window algorithm

func NewTokenBucketAlgorithm

func NewTokenBucketAlgorithm() Algorithm

NewTokenBucketAlgorithm Creates the token bucket algorithm

type AlgorithmMetrics

type AlgorithmMetrics struct {
	Current   int64     // Current value (concurrency count/token usage/request count)
	Limit     int64     // Limit value
	Remaining int64     // remaining quota
	ResetAt   time.Time // Reset time
}

AlgorithmMetrics algorithm metrics

type AlgorithmType

type AlgorithmType string

AlgorithmType algorithm type

const (
	// AlgorithmTokenBucket token bucket algorithm
	AlgorithmTokenBucket AlgorithmType = "token_bucket"

	// AlgorithmSlidingWindow Sliding Window Algorithm
	AlgorithmSlidingWindow AlgorithmType = "sliding_window"

	// AlgorithmConcurrency concurrency rate limiting algorithm
	AlgorithmConcurrency AlgorithmType = "concurrency"

	// Algorithm Adaptive for rate limiting
	AlgorithmAdaptive AlgorithmType = "adaptive"
)

type AllowedEvent

type AllowedEvent struct {
	BaseEvent
	Remaining int64
	Limit     int64
}

AllowedEvent permitted events

type BaseEvent

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

BaseEvent basic event

func NewBaseEvent

func NewBaseEvent(eventType EventType, resource string, ctx context.Context) BaseEvent

NewBaseEvent creates a base event

func (*BaseEvent) Context

func (e *BaseEvent) Context() context.Context

Context returns the context

func (*BaseEvent) Resource

func (e *BaseEvent) Resource() string

Resource returns resource

func (*BaseEvent) Timestamp

func (e *BaseEvent) Timestamp() time.Time

Return timestamp

func (*BaseEvent) Type

func (e *BaseEvent) Type() EventType

Type Return event type

type Config

type Config struct {
	// Enabled whether to enable rate limiting (false means direct passthrough)
	Enabled bool `mapstructure:"enabled"`

	// StoreType storage type: memory, redis
	StoreType string `mapstructure:"store_type"`

	// Redis configuration (required when StoreType is redis)
	Redis RedisInstanceConfig `mapstructure:"redis"`

	// EventBusBuffer event bus buffer size
	EventBusBuffer int `mapstructure:"event_bus_buffer"`

	// KeyFunc resource key generation method (for middleware)
	// Optional values: path, ip, user, path_ip, api_key (default is path)
	KeyFunc string `mapstructure:"key_func"`

	// SkipPaths list of paths to bypass rate limiting (for middleware)
	SkipPaths []string `mapstructure:"skip_paths"`

	// Default resource configuration (if a valid default is set, it will be automatically applied to unconfigured resources)
	Default ResourceConfig `mapstructure:"default"`

	// Resources configuration level (overrides Default)
	Resources map[string]ResourceConfig `mapstructure:"resources"`
}

Rate limiter configuration

func DefaultConfig

func DefaultConfig() Config

Return default configuration

func (*Config) GetResourceConfig

func (c *Config) GetResourceConfig(resource string) ResourceConfig

GetResourceConfig Retrieve resource configuration (prioritize resource-level configuration, fallback to default)

func (*Config) Validate

func (c *Config) Validate() error

Validate configuration

type Event

type Event interface {
	Type() EventType
	Resource() string
	Context() context.Context
	Timestamp() time.Time
}

Event interface

type EventBus

type EventBus interface {
	// Subscribe to event
	Subscribe(listener EventListener)

	// Publish event
	Publish(event Event)

	// Close event bus
	Close()
}

EventBus event bus interface

func NewEventBus

func NewEventBus(bufferSize int) EventBus

Create event bus

type EventListener

type EventListener interface {
	OnEvent(event Event)
}

EventListener event listener interface

type EventListenerFunc

type EventListenerFunc func(event Event)

EventListenerFunc event listener function type

func (EventListenerFunc) OnEvent

func (f EventListenerFunc) OnEvent(event Event)

OnEvent implements EventListener interface

type EventType

type EventType string

Event Type

const (
	// EventAllowed permission granted
	EventAllowed EventType = "allowed"

	// EventRejected reject request
	EventRejected EventType = "rejected"

	// EventWaitStart Start waiting
	EventWaitStart EventType = "wait_start"

	// EventWaitSuccess wait successful
	EventWaitSuccess EventType = "wait_success"

	// EventWaitTimeout wait timeout
	EventWaitTimeout EventType = "wait_timeout"

	// EventLimitChanged Threshold change for rate limiting (adaptive)
	EventLimitChanged EventType = "limit_changed"
)

type LimitChangedEvent

type LimitChangedEvent struct {
	BaseEvent
	OldLimit    int64
	NewLimit    int64
	CPUUsage    float64
	MemoryUsage float64
	SystemLoad  float64
}

LimitChangedEvent Throttling threshold change event (adaptive)

type Limiter

type Limiter interface {
	// Allow check if the request is permitted (quick check)
	Allow(ctx context.Context, resource string) (bool, error)

	// AllowN checks if N requests are permitted
	AllowN(ctx context.Context, resource string, n int64) (bool, error)

	// Wait for permission acquisition (blocking wait, supports timeout)
	Wait(ctx context.Context, resource string) error

	// Wait for N licenses to be available
	WaitN(ctx context.Context, resource string, n int64) error

	// GetMetrics Retrieve metric snapshot
	GetMetrics(resource string) *MetricsSnapshot

	// GetEventBus Obtain the event bus (for subscribing to events)
	GetEventBus() EventBus

	// Reset rate limiter state
	Reset(resource string)

	// Close the rate limiter (clean up resources)
	Close() error

	// Check if the rate limiter is enabled
	IsEnabled() bool
}

Limiter core interface

type Manager

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

Rate Limiter Manager

func NewManager

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

Create rate limiter manager

func NewManagerWithLogger

func NewManagerWithLogger(config Config, ctxLogger *logger.CtxZapLogger, redisClient *redis.Client, provider AdaptiveProvider) (*Manager, error)

Create a rate limiter manager with logger

func (*Manager) Allow

func (m *Manager) Allow(ctx context.Context, resource string) (bool, error)

Allow check if the request is permitted

func (*Manager) AllowN

func (m *Manager) AllowN(ctx context.Context, resource string, n int64) (bool, error)

AllowN checks if N requests are permitted

func (*Manager) Close

func (m *Manager) Close() error

Close Manager

func (*Manager) GetConfig

func (m *Manager) GetConfig() Config

GetConfig retrieve rate limiter configuration

func (*Manager) GetEventBus

func (m *Manager) GetEventBus() EventBus

GetEventBus obtain event bus

func (*Manager) GetMetrics

func (m *Manager) GetMetrics(resource string) *MetricsSnapshot

GetMetrics retrieves throttling metrics

func (*Manager) IsEnabled

func (m *Manager) IsEnabled() bool

Check if the rate limiter is enabled

func (*Manager) Reset

func (m *Manager) Reset(resource string)

Reset the rate limiter status

func (*Manager) SetMetrics

func (m *Manager) SetMetrics(metrics *OTelMetrics)

SetMetrics injects the OTel metrics provider. This should be called after the Manager is created when metrics are enabled.

func (*Manager) Shutdown

func (m *Manager) Shutdown() error

Implements the samber/do.Shutdownable interface for shutdown functionality

func (*Manager) Wait

func (m *Manager) Wait(ctx context.Context, resource string) error

Wait for permission to be acquired

func (*Manager) WaitN

func (m *Manager) WaitN(ctx context.Context, resource string, n int64) error

Wait for N licenses to be acquired

type MetricsCollector

type MetricsCollector interface {
	// RecordAllowed records allowed requests
	RecordAllowed(remaining int64)

	// RecordRejected Request for record rejected
	RecordRejected(reason string)

	// GetSnapshot Retrieve metric snapshot
	GetSnapshot() *MetricsSnapshot

	// Reset metrics
	Reset()
}

MetricsCollector metric collector interface

func NewMetricsCollector

func NewMetricsCollector(resource string, algorithm string) MetricsCollector

Create metric collector

type MetricsConfig

type MetricsConfig struct {
	Enabled          bool
	RecordTokens     bool
	RecordRejectRate bool
}

MetricsConfig holds configuration for limiter metrics

type MetricsSnapshot

type MetricsSnapshot struct {
	Resource      string
	Algorithm     string
	TotalRequests int64
	Allowed       int64
	Rejected      int64
	CurrentValue  int64   // Current value (concurrency count/token count/request count)
	Limit         int64   // Limit value
	Remaining     int64   // remaining quota
	RejectRate    float64 // rejection rate
	LastResetAt   time.Time
}

MetricsSnapshot metric snapshot

type OTelMetrics

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

OTelMetrics implements MetricsProvider for OpenTelemetry integration. This replaces the legacy atomic-based metrics with OTel instrumentation.

func NewOTelMetrics

func NewOTelMetrics(cfg MetricsConfig) *OTelMetrics

NewOTelMetrics creates a new OTel metrics provider for limiter

func (*OTelMetrics) IsMetricsEnabled

func (m *OTelMetrics) IsMetricsEnabled() bool

IsMetricsEnabled returns whether metrics collection is enabled

func (*OTelMetrics) IsRegistered

func (m *OTelMetrics) IsRegistered() bool

IsRegistered returns whether metrics have been registered

func (*OTelMetrics) MetricsName

func (m *OTelMetrics) MetricsName() string

MetricsName returns the metrics group name

func (*OTelMetrics) RecordAllowed

func (m *OTelMetrics) RecordAllowed(ctx context.Context, resource, algorithm string)

RecordAllowed records an allowed request

func (*OTelMetrics) RecordRejected

func (m *OTelMetrics) RecordRejected(ctx context.Context, resource, algorithm, reason string)

RecordRejected records a rejected request

func (*OTelMetrics) RegisterMetrics

func (m *OTelMetrics) RegisterMetrics(meter metric.Meter) error

RegisterMetrics registers all limiter metrics with the provided Meter

func (*OTelMetrics) RegisterTokenCallback

func (m *OTelMetrics) RegisterTokenCallback(resource string, callback func() int64)

RegisterTokenCallback registers a callback for a resource's token count

func (*OTelMetrics) UnregisterTokenCallback

func (m *OTelMetrics) UnregisterTokenCallback(resource string)

UnregisterTokenCallback removes a resource's token callback

type RedisInstanceConfig

type RedisInstanceConfig struct {
	Instance  string `mapstructure:"instance"`   // Redis instance name (configured in redis.instances)
	KeyPrefix string `mapstructure:"key_prefix"` // Redis key prefix (default "limiter:")
}

RedisInstanceConfig Redis instance reference configuration (reusing kernel redis component)

type RedisStore

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

RedisStore Redis storage implementation

func NewRedisStore

func NewRedisStore(client *redis.Client, keyPrefix string) *RedisStore

NewRedisStore creates Redis storage

func (*RedisStore) Close

func (s *RedisStore) Close() error

Close Close the connection (RedisStore does not own the client, so there is no need to close)

func (*RedisStore) Decr

func (s *RedisStore) Decr(ctx context.Context, key string) (int64, error)

Decrement atomic decrement

func (*RedisStore) DecrBy

func (s *RedisStore) DecrBy(ctx context.Context, key string, delta int64) (int64, error)

Atomically decrement by the specified value

func (*RedisStore) Del

func (s *RedisStore) Del(ctx context.Context, keys ...string) error

Delete key deletion

func (*RedisStore) Eval

func (s *RedisStore) Eval(ctx context.Context, script string, keys []string, args []interface{}) (interface{}, error)

Evaluate execution of Lua script

func (*RedisStore) Exists

func (s *RedisStore) Exists(ctx context.Context, key string) (bool, error)

Exists check if key exists

func (*RedisStore) Expire

func (s *RedisStore) Expire(ctx context.Context, key string, expiration time.Duration) error

Set expiration time

func (*RedisStore) Get

func (s *RedisStore) Get(ctx context.Context, key string) (string, error)

Get Retrieve value (string)

func (*RedisStore) GetInt64

func (s *RedisStore) GetInt64(ctx context.Context, key string) (int64, error)

GetInt64 get integer value

func (*RedisStore) Incr

func (s *RedisStore) Incr(ctx context.Context, key string) (int64, error)

Increment atomic increment

func (*RedisStore) IncrBy

func (s *RedisStore) IncrBy(ctx context.Context, key string, value int64) (int64, error)

IncrBy atomic increment by specified value

func (*RedisStore) Set

func (s *RedisStore) Set(ctx context.Context, key string, value string, ttl time.Duration) error

Set the value (string)

func (*RedisStore) SetInt64

func (s *RedisStore) SetInt64(ctx context.Context, key string, value int64, ttl time.Duration) error

SetInt64 set integer value

func (*RedisStore) TTL

func (s *RedisStore) TTL(ctx context.Context, key string) (time.Duration, error)

Get the remaining time-to-live for the key Returns 0 if key doesn't exist or has no TTL

func (*RedisStore) ZAdd

func (s *RedisStore) ZAdd(ctx context.Context, key string, score float64, member string) error

Add ordered set members

func (*RedisStore) ZCount

func (s *RedisStore) ZCount(ctx context.Context, key string, min, max float64) (int64, error)

ZCount statistics the number of members in a sorted set within a specified score range

func (*RedisStore) ZRemRangeByScore

func (s *RedisStore) ZRemRangeByScore(ctx context.Context, key string, min, max float64) error

Remove members from a sorted set that are within a specified score range

type RejectedEvent

type RejectedEvent struct {
	BaseEvent
	RetryAfter time.Duration
	Reason     string
}

RejectedEvent rejected event

type ResourceConfig

type ResourceConfig struct {
	// Algorithm rate_limiting: token_bucket, sliding_window, concurrency, adaptive
	Algorithm string `mapstructure:"algorithm"`

	// Token bucket configuration
	Rate       int64 `mapstructure:"rate"`        // token generation rate (per second)
	Capacity   int64 `mapstructure:"capacity"`    // bucket capacity
	InitTokens int64 `mapstructure:"init_tokens"` // Initial token count

	// Sliding window configuration
	Limit      int64         `mapstructure:"limit"`       // maximum request count within window
	WindowSize time.Duration `mapstructure:"window_size"` // window size
	BucketSize time.Duration `mapstructure:"bucket_size"` // bucket size

	// Concurrent rate limiting configuration
	MaxConcurrency int64         `mapstructure:"max_concurrency"` // maximum concurrency limit
	Timeout        time.Duration `mapstructure:"timeout"`         // timeout waiting

	// Adaptive rate limiting configuration
	MinLimit       int64         `mapstructure:"min_limit"`       // minimum rate limiting value
	MaxLimit       int64         `mapstructure:"max_limit"`       // maximum rate limiting value
	TargetCPU      float64       `mapstructure:"target_cpu"`      // Target CPU utilization rate
	TargetMemory   float64       `mapstructure:"target_memory"`   // Target memory utilization rate
	TargetLoad     float64       `mapstructure:"target_load"`     // target system load
	AdjustInterval time.Duration `mapstructure:"adjust_interval"` // Adjust interval
}

ResourceConfig resource-level configuration

func DefaultResourceConfig

func DefaultResourceConfig() ResourceConfig

Returns default resource configuration

func (ResourceConfig) Merge

func (rc ResourceConfig) Merge(override ResourceConfig) ResourceConfig

Merge merge configuration (override default values)

func (*ResourceConfig) Validate

func (rc *ResourceConfig) Validate() error

Validate resource configuration

type Response

type Response struct {
	// Allowed 是否允许: Is allowed
	Allowed bool

	// RetryAfter suggests retry time (valid when Allowed=false)
	RetryAfter time.Duration

	// Remaining quota (token bucket/sliding window)
	Remaining int64

	// Limit total quota
	Limit int64

	// ResetTime quota reset time
	ResetAt time.Time
}

Rate limiting response

type Store

type Store interface {
	// Get retrieve value
	Get(ctx context.Context, key string) (string, error)

	// Set value (with expiration time)
	Set(ctx context.Context, key string, value string, ttl time.Duration) error

	// GetInt64 get integer value
	GetInt64(ctx context.Context, key string) (int64, error)

	// SetInt64 set integer value
	SetInt64(ctx context.Context, key string, value int64, ttl time.Duration) error

	// Atomic increment
	Incr(ctx context.Context, key string) (int64, error)

	// IncrBy atomic increment by specified value
	IncrBy(ctx context.Context, key string, delta int64) (int64, error)

	// Atomic decrement
	Decr(ctx context.Context, key string) (int64, error)

	// Atomically decrement by the specified value
	DecrBy(ctx context.Context, key string, delta int64) (int64, error)

	// Set expiration time
	Expire(ctx context.Context, key string, ttl time.Duration) error

	// Get remaining TTL (Time To Live) duration
	TTL(ctx context.Context, key string) (time.Duration, error)

	// Delete delete key
	Del(ctx context.Context, keys ...string) error

	// Exists Check if key exists
	Exists(ctx context.Context, key string) (bool, error)

	// Add to sorted set
	ZAdd(ctx context.Context, key string, score float64, member string) error

	// Remove by score range
	ZRemRangeByScore(ctx context.Context, key string, min, max float64) error

	// ZCount statistics the number of elements within a score range
	ZCount(ctx context.Context, key string, min, max float64) (int64, error)

	// Eval executes Lua scripts (specific to Redis, can return unsupported errors for in-memory storage)
	Eval(ctx context.Context, script string, keys []string, args []interface{}) (interface{}, error)

	// Close connection
	Close() error
}

Store interface (Strategy Pattern)

func NewMemoryStore

func NewMemoryStore() Store

Create memory store

type StoreType

type StoreType string

StoreType storage type

const (
	// StoreTypeMemory Memory Storage
	StoreTypeMemory StoreType = "memory"

	// StoreTypeRedis Redis storage
	StoreTypeRedis StoreType = "redis"
)

type ValidationError

type ValidationError struct {
	Resource string
	Field    string
	Message  string
	Err      error
}

ValidationError configuration validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WaitEvent

type WaitEvent struct {
	BaseEvent
	Success bool
	Waited  time.Duration
}

WaitEvent waiting event

Jump to

Keyboard shortcuts

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