PHP经验分享程序员

lumen接口访问频率throttle

2019-03-08  本文已影响5人  weylau

由于公司项目对外提供开放平台接口,所以为了防止第三方调用接口太频繁给服务器带来过大的压力,需要对接口调用次数限制,我使用的限制规则是每个ip每个接口一分钟之内最多访问30次,目前项目是使用的lumen框架开发的接口,这里主要说一下如何在Lumen框架中使用throttle中间件来限制客户端接口请求次数

新建中间件

在app\Http\Middleware中新建ThrottleRequests.php文件,文件下载地址:https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php
修改ThrottleRequests.php中的resolveRequestSignature方法用来定义我们自己的限制规则

protected function resolveRequestSignature($request){
        return sha1(
            $request->method() .
            '|' . $request->path() .
            $request->getClientIp()
        );
}

异常处理

在app/Exceptions中新建ThrottleException.php,当访问次数超过限制时抛出异常

<?php
namespace App\Exceptions;

use Exception;

class ThrottleException extends Exception
{
    protected $isReport = false;

    public function isReport()
    {
        return $this->isReport;
    }
}

在app/Exceptions/Handler.php捕获该抛出异常,在render方法增加以下判断:

if ($e instanceof ThrottleException) {
            return response(['code' => $e->getCode(), 'msg' => $e->getMessage()], 432);
 }

修改ThrottleRequests.php文件中的buildException方法

protected function buildException($key, $maxAttempts)
    {
        $retryAfter = $this->getTimeUntilNextRetry($key);

        $headers = $this->getHeaders(
            $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
            $retryAfter
        );

        return new ThrottleException('Too Many Attempts.', 432);
    }

注册中间件

在bootstrap/app.php中注册

$app->routeMiddleware([
     'throttle' => App\Http\Middleware\ThrottleRequests::class,
]);

使用

$router->group(['middleware' => ['throttle:30']],function() use ($router){
    $router->post('test','TestController@test');
});

throttle:30 表示1分钟之内访问30次
throttle:30,2 表示2分钟之内访问30次

上一篇 下一篇

猜你喜欢

热点阅读