redis-cell漏斗限流算法实现接口高并发限流

官方介绍:

A Redis module that provides rate limiting in Redis as a single command. Implements the fairly sophisticated generic cell rate algorithm (GCRA) which provides a rolling time window and doesn't depend on a background drip process.

The primitives exposed by Redis are perfect for doing work around rate limiting, but because it's not built in, it's very common for companies and organizations to implement their own rate limiting logic on top of Redis using a mixture of basic commands and Lua scripts (I've seen this at both Heroku and Stripe for example). This can often result in naive implementations that take a few tries to get right. The directive of redis-cell is to provide a language-agnostic rate limiter that's easily pluggable into many cloud architectures.

Informal benchmarks show that redis-cell is pretty fast, taking a little under twice as long to run as a basic Redis SET (very roughly 0.1 ms per command as seen from a Redis client).

大概意思就是:一个Redis模块,可作为单个命令在Redis中提供速率限制。实现相当复杂的通用信元速率算法(GCRA),该算法提供滚动时间窗口,不依赖于后台滴注过程。此处省略……………………最后一点就是,redis-cell速度非常快

redis-cell是一个用rust语言编写的基于令牌桶算法的的限流模块,提供原子性的限流功能,并允许突发流量,可以很方便的应用于分布式环境中,这样子限流问题就非常简单了(redis 4.0 以后开始支持扩展模块)

redis-cell令牌桶限流算法原理及步骤

令牌桶算法的原理是定义一个按一定速率产生token的桶,每次去桶中申请token,若桶中没有足够的token则申请失败,否则成功。在请求不多的情况下,桶中的token基本会饱和,此时若流量激增,并不会马上拒绝请求,所以这种算法允许一定的流量激增。

Redis Cell的使用

该模块只提供了一个命令:CL.THROTTLE

CL.THROTTLE user123 15 30 60 1
               ▲     ▲  ▲  ▲ ▲
               |     |  |  | └───── apply 1 token (default if omitted)
               |     |  └──┴─────── 30 tokens / 60 seconds  速度
               |     └───────────── 15 max_burst            漏斗容量
               └─────────────────── key "user123"           key

上面这个指令的意思是允许「用户user123回复行为」的频率为每 60s 最多 30 次(漏水速
率),漏斗的初始容量为 15,也就是说一开始可以连续请求 15 次,然后才开始受漏水
速率的影响。

Response

127.0.0.1:6379> CL.THROTTLE user123 15 30 60
1) (integer) 0    # 0 表示允许,1表示拒绝
2) (integer) 16   # 漏斗容量
3) (integer) 15   # 漏斗剩余空间
4) (integer) -1   # 如果拒绝了,需要多长时间后再试(漏斗有空间了,单位秒)
5) (integer) 2    # 多长时间后,漏斗完全空出来

详细介绍请参考:https://github.com/brandur/redis-cell

thinkphp5.1 结合redis-cell实现接口限流demo,喜欢的朋友可以关注一下。

猜你喜欢

转载自blog.csdn.net/liuxl57805678/article/details/108824411