redis限流

1、基于Redis的数据结构zset

用的redis的zset来计数,score字段寸时间戳,每次请求增加一条数据,并按score移除超时的数据。

最后在给整个key1加个过期时间

2、基于Redis的令牌桶算法

具体代码实现:

https://blog.csdn.net/weixin_42645678/article/details/124428393

  1. 根据tokenKey查询最后一次剩余令牌数last_tokens,如果查不到,说明当前令牌是满的last_tokens=capcity;
  2. 再去根据timestamp_key查询上次消费令牌的时间戳last_refreshed,不存在就给0;
  3. 根据上次消费令牌的时间戳和当前时间戳算出时间间隔,再根据令牌生成速率,计算剩余令牌数量 filled_tokens = math.min(capacity, last_tokens+(delta*rate));
  4. 对比剩余令牌数量和请求的令牌数量,如果满足就通过,否则就不通过;
  5. 最后更新tokenKey、timestamp_key

 

 

 

 

 

 

 

posted @ 2023-12-02 12:54  guoyu1  阅读(19)  评论(0)    收藏  举报