YII2 restful 限流

Kornan
2020-11-01 / 0 评论 / 109 阅读 / 正在检测是否收录...

之前用豆瓣的API时,会有一分钟只能请求40次的限制;通过Yii2来实现这样的限制:

    public static function tryLimit($key, $prefix, $timeLimit, $tryTimes){
        $times = Yii::$app->cache->get($key . $prefix);
        if (!$times) {
            $times = 0;
        }
        if ($times >= $tryTimes) { //一小时只能获取$tryTimes次
            throw new TooManyRequestsHttpException("Too Many Requests");
        } else {
            Yii::$app->cache->set($key . $prefix, $times + 1, $timeLimit);
        }
    }

    public static function controllerLimit($params, $funcName)
    {
        foreach ($params as $v) {
            if ($v['funciton'] == $funcName) {
                self::tryLimit($v['funciton'], (string)Yii::$app->request->userIP, $v['time_limit'], $v['try_times']);
            }
        }
    }

在xxxController加入限制

    public function init()
    {
        if (in_array(Yii::$app->requestedRoute, [
            'user/info'
        ])) {
            //限制IP访问接口次数(60秒访问只能访问40次)
            self::controllerLimit([
                [
                    'funciton' => 'user/info',
                    'time_limit' => 60,
                    'try_times' => 40,
                ]
            ], Yii::$app->requestedRoute);
        }
    }
0

评论

博主关闭了当前页面的评论