限流器
令牌桶、滑动窗口与分布式限流
在线 Playground
在浏览器中直接体验本页相关 API,无需本地安装 Go 环境。
限流器
统一限流与并发控制,支持令牌桶、按 Key 限流及 Redis/MongoDB/etcd 分布式后端。
go get github.com/LingByte/ling-base/common/limiter
go get github.com/LingByte/ling-base/common/limiter/tokenbucket以下为
common/limiter包 README 全文。
A unified rate-limiting and concurrency-control interface with multiple pluggable backends. Follows the "one interface, many backends" pattern.
Interfaces
// Core concurrency control
type Limiter interface {
Running() int
Acquire(ctx context.Context, key []byte) error
Release(key []byte)
}
// String-keyed convenience variant
type StringLimiter interface {
Running() int
Acquire(ctx context.Context, key string) error
Release(key string)
}
// Byte-size-aware (bandwidth / storage quotas)
type SizeLimiter interface {
Running() int64
Acquire(ctx context.Context, key []byte, size int64) error
Release(key []byte, size int64)
Remaining(key []byte) int64
}Implementations
| Package | Type | Description |
|---|---|---|
count/ | Concurrency | Global concurrency cap (atomic or blocking) |
keycount/ | Concurrency | Per-key concurrency cap (mutex, sync-atomic, or blocking) |
keysize/ | Size | Per-key cumulative byte-size cap |
tokenbucket/ | Rate | Token-bucket rate limiter (QPS / burst) |
null/ | — | No-op implementation (disable limiting) |
redis/ | Distributed | Redis-backed sliding window, token bucket, concurrency |
memcached/ | Distributed | Memcached-backed sliding window, concurrency |
mongodb/ | Distributed | MongoDB-backed rate limit, concurrency |
etcd/ | Distributed | etcd-backed rate limit, concurrency |
Usage
import (
"github.com/LingByte/ling-base/common/limiter"
"github.com/LingByte/ling-base/common/limiter/count"
"github.com/LingByte/ling-base/common/limiter/keycount"
"github.com/LingByte/ling-base/common/limiter/tokenbucket"
)
// Global max 100 concurrent
l := count.New(100)
if err := l.Acquire(nil); err != nil {
// limit exceeded
}
defer l.Release(nil)
// Per-user max 5 concurrent
l := keycount.New(5)
l.Acquire(nil, []byte("user123"))
defer l.Release([]byte("user123"))
// 100 QPS, burst 200
l := tokenbucket.New(100, 200)
if err := l.Acquire(nil); err != nil {
// rate limited
}
// String-keyed helper
if err := limiter.AcquireString(l, ctx, "user123"); err != nil {
// limit exceeded
}
defer limiter.ReleaseString(l, "user123")Errors
| Error | Meaning |
|---|---|
ErrLimitExceeded | Acquire cannot grant a permit (non-blocking mode) |
ErrKeyRequired | Implementation requires a non-empty key |
ErrInvalidLimit | Configured limit is ≤ 0 |
ErrInvalidSize | Requested size is ≤ 0 |
Testing
All implementations have unit tests. Distributed backends use in-memory mocks
or miniredis — no external servers required.
License
MIT