固定窗口限流实现简单但存在突增问题,滑动窗口更平滑精确,令牌桶支持突发流量,Golang可用rate库实现;分布式场景推荐Redis+Lua脚本进行集群限流。

微服务架构中,限流是保障系统稳定性的重要手段。Golang 因其高并发和高性能特性,非常适合构建需要精细控制流量的微服务。实现限流策略的核心目标是在高并发场景下防止服务被压垮,保护后端资源。下面介绍几种常见的限流方式及 Golang 实践示例。
固定窗口限流是最简单的实现方式,将时间划分为固定长度的窗口,在每个窗口内限制请求次数。
例如:每分钟最多允许 100 次请求。
优点:实现简单;缺点:存在“突发流量”问题,可能在窗口切换时出现双倍请求通过。示例代码:
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"sync"
"time"
)</p><p>type FixedWindowLimiter struct {
maxCount int
window time.Duration
count int
lastReset time.Time
mu sync.Mutex
}</p><p>func NewFixedWindowLimiter(maxCount int, window time.Duration) *FixedWindowLimiter {
return &FixedWindowLimiter{
maxCount: maxCount,
window: window,
lastReset: time.Now(),
}
}</p><p>func (l *FixedWindowLimiter) Allow() bool {
l.mu.Lock()
defer l.mu.Unlock()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">now := time.Now()
if now.Sub(l.lastReset) > l.window {
l.count = 0
l.lastReset = now
}
if l.count < l.maxCount {
l.count++
return true
}
return false}
相比固定窗口,滑动窗口能更平滑地计算请求数,避免突增问题。它记录每个请求的时间戳,并判断过去一个窗口时间内是否超过阈值。
示例实现:
type SlidingWindowLimiter struct {
maxCount int
window time.Duration
requests []time.Time
mu sync.Mutex
}
<p>func NewSlidingWindowLimiter(maxCount int, window time.Duration) *SlidingWindowLimiter {
return &SlidingWindowLimiter{
maxCount: maxCount,
window: window,
}
}</p><p>func (l *SlidingWindowLimiter) Allow() bool {
l.mu.Lock()
defer l.mu.Unlock()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">now := time.Now()
cutOff := now.Add(-l.window)
// 删除过期请求
i := 0
for _, t := range l.requests {
if t.After(cutOff) {
l.requests[i] = t
i++
}
}
l.requests = l.requests[:i]
if len(l.requests) < l.maxCount {
l.requests = append(l.requests, now)
return true
}
return false}
令牌桶是一种更灵活的限流算法,以恒定速率生成令牌,每个请求消耗一个令牌。允许一定程度的突发流量,只要桶中有足够令牌即可通过。
Golang 标准库 golang.org/x/time/rate 提供了开箱即用的实现。
使用示例:
package main
<p>import (
"fmt"
"golang.org/x/time/rate"
"time"
)</p><p>func main() {
// 每秒产生 5 个令牌,桶容量为 10
limiter := rate.NewLimiter(5, 10)</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">for i := 0; i < 15; i++ {
if limiter.Allow() {
fmt.Printf("Request %d allowed at %v\n", i, time.Now())
} else {
fmt.Printf("Request %d denied\n", i)
}
time.Sleep(100 * time.Millisecond)
}}
单机限流在微服务集群中不够用,需借助 Redis 等中间件实现分布式限流。常用方案是基于 Redis 的 Lua 脚本实现原子性操作。
Redis + Lua 实现滑动窗口限流脚本:
-- KEYS[1]: key
-- ARGV[1]: window size in seconds
-- ARGV[2]: max count
local key = KEYS[1]
local window = tonumber(ARGV[1])
local max_count = tonumber(ARGV[2])
local now = redis.call('TIME')[1]
<p>-- 清理过期数据
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)</p><p>-- 获取当前请求数
local current = redis.call('ZCARD', key)</p><p>if current < max_count then
redis.call('ZADD', key, now, now)
redis.call('EXPIRE', key, window)
return 1
else
return 0
end
Golang 调用示例:
import (
"context"
"github.com/go-redis/redis/v8"
)
<p>var ctx = context.Background()</p><p>func allowByRedis(client *redis.Client, key string, windowSec, maxCount int) (bool, error) {
script := <code> local key = KEYS[1] local window = tonumber(ARGV[1]) local max_count = tonumber(ARGV[2]) local now = redis.call('TIME')[1] redis.call('ZREMRANGEBYSCORE', key, 0, now - window) local current = redis.call('ZCARD', key) if current < max_count then redis.call('ZADD', key, now, now) redis.call('EXPIRE', key, window) return 1 else return 0 end </code></p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">result, err := client.Eval(ctx, script, []string{key}, windowSec, maxCount).Result()
if err != nil {
return false, err
}
return result == int64(1), nil}
基本上就这些。根据实际场景选择合适的限流策略:单机可用 rate.Limiter,追求精度可用滑动窗口,集群环境推荐 Redis + Lua 方案。合理配置限流规则,能有效提升微服务的容错能力和可用性。
以上就是Golang如何实现微服务限流策略_Golang 微服务流控实践示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号