php基于redis的list型数据结构实现ip限流操作

    /**
     * 检查队列的长度是否到达设定的阈值,已到达则返回false,未到达则将当前时间戳推入队列最末端,同时刷新队列整体的缓存时间
     * @param $key 队列缓存的key
     * @param $expire 队列缓存过期时间,例如上面例子中的5秒
     * @param $limit 队列长度阈值,如上面例子中的3次
     * @return bool
     */
    public function checkLimit($key, $expire, $limit)
    {
        $length = $this->refreshList($key, $expire);
        if ($length < $limit) {
            $redis = new Redis();
            // 未到达访问限制,将当前时间戳推入到list的最后边,同时把整个key的过期时间重新更新
            $redis->rPush($key, time());
            $redis->expire($key, intval($expire));
            return true;
        }
        return false;
    }
    /**
     * 刷新队列,过滤掉已经不在有效时间内的值,返回最新队列的长度
     * @param $key string 自定义的缓存key
     * @param $expire 队列缓存过期时间,例如上面例子中的5秒
     * @return bool|int
     */
    public function refreshList ($key, $expire)
    {
        $redis = new Redis();
        if ($redis->has($key)) {
            do { // 对于已存在数据的list,要先从前往后把已经过期的数据弹出
                $oldest_value = $redis->lPop($key);
            } while ($oldest_value && time() - $oldest_value > $expire);
            // 把最后弹出的数据重新塞回list的最前边
            $oldest_value && $redis->lPush($key, $oldest_value);
            return $redis->lLen($key);
        }
        return 0;
    }
posted @ 2021-02-24 16:48  liu·bear  阅读(108)  评论(0)    收藏  举报