php下Yii2用redis实现接口访问频率限制

基于访问ip做的访问频率限制

class Limit
{
    /**
     * api 访问频率限制
     * @param $ip
     * @param int $timeout
     * @param string $path
     */
    public static function requestLimit($ip = null, $timeout = 0, $path = '')
    {
        if (empty($ip) {
            $ip = \Yii::$app->request->userIP;
        }
        if ($timeout <= 0) {
            $timeout = \Yii::$app->params['api_req_limit_interval'] ?? 3;
        }
        if (empty($path)) {
            $path = self::getApiPath();
        }
        $lock_key = "limit:" . $ip . ":" . $path;
        $redis = \Yii::$app->redis;
        return $redis->executeCommand('set', [$lock_key, time(), 'EX', $timeout, 'NX']);
    }

    /**
     * 获取当前访问路径
     * @return string
     */
    public static function getApiPath()
    {
        $route = \Yii::$app->controller->getRoute();
        return "/" . $route;
    }
}

调用方法:

if (Limit::requestLimit()) {
    return $this->error("您的访问频率过快,请休息会儿再来");
}

你可能感兴趣的:(php)