zoukankan      html  css  js  c++  java
  • python 实现限流

    固定窗口

    固定窗口就是记录一个固定的时间窗口内的操作次数,操作次数超过阈值则进行限流。

    def fix_window_limit(redis_obj, period, max_count):
        """
        固定窗口
        :param redis_obj:redis连接对象
        :param period: 周期 秒为单位
        :param max_count: 最大请求数量数量
        :return:
        """
        key = "global_limit"
        current = redis_obj.get(key)
        if current:
            current = int(current.decode('utf-8'))
            if current >= max_count:
                return False
        value = r.incr(key)
        if value == 1:
            r.expire(key, period)
        return True
    
    

    滑动窗口

    滑动窗口就是记录一个滑动的时间窗口内的操作次数,操作次数超过阈值则进行限流。

    def rolling_window_limit(redis_obj, period, max_count):
        """
        滑动窗口
        :param redis_obj:redis连接对象
        :param period: 周期 秒为单位
       :param max_count: 最大请求数量数量
        :return:
        """
        key = "global_limit"
        now_time = int(time.time()*1000)
        # 使用管道
        pipe = redis_obj.pipeline()
        pipe.multi()
        # 添加当前操作当zset中
        pipe.zadd(key, {str(now_time): now_time})
        # 整理zset,删除时间窗口外的数据
        pipe.zremrangebyscore(key, 0, now_time - period * 1000)
        # 获取当前窗口的数量
        pipe.zcard(key)
        pipe.expire(key, period+1)
        result = pipe.execute()
        pipe.close()
        return result[-2] <= max_count
    
    
    此时此刻,非我莫属
  • 相关阅读:
    [SDOI2006] 保安站岗
    [NOIP2003] 传染病控制
    [USACO13OPEN] 照片Photo
    [HNOI/AHOI2018] 道路
    [TJOI2007] 线段
    [HAOI2009] 逆序对数列
    codeforces|CF1054D Changing Array
    hihoCoder 1785
    luogu 1712
    luogu 3248
  • 原文地址:https://www.cnblogs.com/taozhengquan/p/15529648.html
Copyright © 2011-2022 走看看