令牌桶算法实现限流
前言
高并发场景下,为了保障服务的高可用(过载保护),除了使用消息中间件做流量削峰之外,还可以在网关侧做限流;
而令牌桶则是常见的限流算法,本文简单记录下。
Token bucket
主要思想
1. There is a bucket of a token that can hold up the number of burst
at most.
2. We will add tokens into this bucket at a rate of N per second. If the bucket is full, no more tokens are added to this bucket. We call this rate as rate
.
3. When there are requests, we will take the corresponding number of tokens from the bucket. If the bucket is empty, block/discard it until enough tokens are put in.
功能实现
1. In the case of running for a long time, the average value of the limited request rate is equal to the rate of adding tokens, the rate
.
2. Allow a certain level of peak flow:
- If the request rate is
M
and is greater thanrate
, the rate of token decreasing isM - rate
. - Therefore, the time for us to take all the tokens from a full bucket is
burst / (M - rate)
, and the number of the requests be accepted isburst / (M - rate) * M
during this period.
All in all, it can be simply understood as rate
is the average request rate and burst
is is the instantaneous maximum request rate.
代码实现
补充
- 漏桶:桶里装的是请求(限制的是最大请求数,超过则丢掉),有缓存,适合秒杀场景(请求量级远超服务能力)
- 令牌桶:桶里装的是令牌/服务能力,无缓存,适合请求数在一定范围内浮动。
出处:http://www.cnblogs.com/standby/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
2017-06-10 Python基础(正则、序列化、常用模块和面向对象)