redis eval 实现限流

大致流程:

  1. 每次请求就写入有序集合里面,集合的sorce值是当前毫秒时间戳(防止秒出现重复),可以认为每一次请求就一个时间戳在里面。

  2. 从集合里面去掉10分钟以前所有的集合数据。然后计算出当前的集合里面数量

  3. 根据这个数量来与我们阈值做大小判断,如果超过就锁住,否则继续走下去

//将我们时间戳写入我们redis的有序集合里面
 Redis::zadd('user:1:request:nums',1561456435,'1561456435.122');
//设置key的过期时间为10分钟
Redis::expire('user:1:request:nums',300);
//删除我们10分钟以前的数据
Redis::ZREMRANGEBYSCORE('user:1:request:nums',0,1561456135);
//获取里面剩下请求个数
$request_nums=(int)Redis::zcard(self::TIMELINE_ELEVEL_KEY);
if($request_nums >= 10){
    //加入小黑屋,下次再进来就要锁定判断
}
...
private final static String TEXT="local ratelimit_info = redis.pcall('HMGET',KEYS[1],'last_time','current_token')\n" +
            "local last_time = ratelimit_info[1]\n" +
            "local current_token = tonumber(ratelimit_info[2])\n" +
            "local max_token = tonumber(ARGV[1])\n" +
            "local token_rate = tonumber(ARGV[2])\n" +
            "local current_time = tonumber(ARGV[3])\n" +
            "if current_token == nil then\n" +
            "  current_token = max_token\n" +
            "  last_time = current_time\n" +
            "else\n" +
            "  local past_time = current_time-last_time\n" +
            "  \n" +
            "  if past_time>1000 then\n" +
            "\t  current_token = current_token+token_rate\n" +
            "\t  last_time = current_time\n" +
            "  end\n" +
            "\n" +
            "  if current_token>max_token then\n" +
            "    current_token = max_token\n" +
            "\tlast_time = current_time\n" +
            "  end\n" +
            "end\n" +
            "\n" +
            "local result = 0\n" +
            "if(current_token>0) then\n" +
            "  result = 1\n" +
            "  current_token = current_token-1\n" +
            "  last_time = current_time\n" +
            "end\n" +
            "redis.call('HMSET',KEYS[1],'last_time',last_time,'current_token',current_token)\n" +
            "return result";

 

### 使用 Redis 实现滑动窗口算法进行限流的最佳实践 #### 1. 滑动窗口限流的特点 滑动窗口限流相比固定窗口限流更加精确,能够更好地处理突发流量。然而,这种实现方式确实更为复杂,并且对Redis的性能有更高的要求,在高并发场景下尤其如此[^1]。 #### 2. 利用 ZSET 数据结构 通过使用 Redis 的 `ZSET` (有序集合),可以在一定时间内记录请求的时间戳并对其进行排序。对于每一个新的请求到来时,程序会移除超过指定时间段之外的数据项,从而保持数据的有效性和准确性[^2]。 #### 3. Pipeline 提升效率 由于涉及到多次与 Redis 进行交互的操作(如增加新成员、删除过期成员以及获取当前计数值等),采用 pipeline 方式批量执行命令能显著减少网络延迟带来的开销,提高整体性能表现。 #### 4. Lua 脚本确保原子性 为了避免竞争条件的发生,推荐利用 Redis 内置的支持事务特性的 Lua 脚本来完成整个流程的一次性提交。这不仅简化了客户端代码的设计难度,同时也保障了操作的安全可靠[^4]。 --- 以下是 Python 版本的一个简单示例来展示如何基于上述原则构建一个高效的滑动窗口限流器: ```python import time from redis import StrictRedis class SlidingWindowRateLimiter(object): def __init__(self, redis_client: StrictRedis, key_prefix='swrl:', window_size=60, max_requests=100): self.redis = redis_client self.key_prefix = key_prefix self.window_size = window_size self.max_requests = max_requests def _get_key(self, identifier): return f"{self.key_prefix}{identifier}" def is_allowed(self, identifier): now_ms = int(time.time() * 1000) key = self._get_key(identifier) lua_script = """ local current_time = tonumber(ARGV[1]) local cutoff_time = current_time - tonumber(ARGV[2]) -- Remove expired entries from the sorted set. redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', '(' .. tostring(cutoff_time)) -- Count remaining items within allowed timeframe. local count = redis.call('ZCOUNT', KEYS[1], '-inf', '+inf') if tonumber(count) >= tonumber(ARGV[3]) then return 0 else redis.call('ZADD', KEYS[1], current_time, current_time) return 1 end """ result = self.redis.eval(lua_script, [key], [ str(now_ms), str(self.window_size*1000), str(self.max_requests)]) return bool(result) if __name__ == "__main__": rdb = StrictRedis(host="localhost", port=6379, db=0) limiter = SlidingWindowRateLimiter(rdb, 'test_api_', 60, 5) user_id = "user_1" for i in range(8): print(f"Attempt {i}: ", limiter.is_allowed(user_id)) ``` 此段代码定义了一个名为 `SlidingWindowRateLimiter` 类用于管理特定 API 接口下的用户访问频率控制逻辑;其中包含了两个主要方法 `_get_key()` 和 `is_allowed()` 。前者负责生成唯一标识符以便区分不同资源对象间的统计数据差异;后者则实现了核心业务功能——即依据传入的身份参数决定是否允许此次调用继续前进还是返回拒绝响应给前端应用层面上做进一步处理。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值