ratelimit

package
v0.6.0 Latest Latest
Warning

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

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

Documentation

Overview

Package ratelimit 提供通用限流机制。

本包定义限流策略、决策结果、Limiter 端口、本地 token bucket 限流器和 基于共享 Backend 的分布式限流器。它不绑定 HTTP、gRPC、Redis keyspace 或业务观测模型;项目层可以把 Decision 映射为自己的响应头、指标或治理事件。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Backend

type Backend interface {
	Allow(ctx context.Context, key string, ratePerSecond float64, burst int) (bool, time.Duration, error)
}

Backend 是 DistributedLimiter 使用的共享 token bucket 存储端口。

type Decision

type Decision struct {
	Allowed           bool
	RetryAfter        time.Duration
	RetryAfterSeconds int
	Policy            Policy
	Outcome           Outcome
}

Decision 表示一次与传输协议无关的限流检查结果。

type DistributedLimiter

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

DistributedLimiter 将共享 token bucket backend 适配为限流决策器。

func NewDistributedLimiter

func NewDistributedLimiter(backend Backend, policy Policy) *DistributedLimiter

func (*DistributedLimiter) Decide

func (l *DistributedLimiter) Decide(ctx context.Context, key string) Decision

type Limiter

type Limiter interface {
	Decide(ctx context.Context, key string) Decision
}

Limiter 决定一个请求 key 是否允许通过。

type LocalLimiter

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

LocalLimiter 是进程内 token bucket 限流器。

func NewKeyedLocalLimiter

func NewKeyedLocalLimiter(policy Policy) *LocalLimiter

func NewLocalLimiter

func NewLocalLimiter(policy Policy) *LocalLimiter

func (*LocalLimiter) Decide

func (l *LocalLimiter) Decide(_ context.Context, key string) Decision

type Outcome

type Outcome string

Outcome 描述一次限流决策的通用结果。

const (
	OutcomeAllowed      Outcome = "allowed"
	OutcomeRateLimited  Outcome = "rate_limited"
	OutcomeDegradedOpen Outcome = "degraded_open"
)

type Policy

type Policy struct {
	Component     string
	Scope         string
	Resource      string
	Strategy      string
	RatePerSecond float64
	Burst         int
}

Policy 描述一个有边界的限流控制点。

func (Policy) Valid

func (p Policy) Valid() bool

Valid 判断策略是否能构造正数 token bucket。

Directories

Path Synopsis
Package redisadapter 提供 ratelimit.Backend 的 Redis 实现。
Package redisadapter 提供 ratelimit.Backend 的 Redis 实现。

Jump to

Keyboard shortcuts

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