美文网首页PHP经验分享程序员
lumen接口访问频率throttle

lumen接口访问频率throttle

作者: weylau | 来源:发表于2019-03-08 10:18 被阅读5次

由于公司项目对外提供开放平台接口,所以为了防止第三方调用接口太频繁给服务器带来过大的压力,需要对接口调用次数限制,我使用的限制规则是每个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次

相关文章

  • lumen接口访问频率throttle

    由于公司项目对外提供开放平台接口,所以为了防止第三方调用接口太频繁给服务器带来过大的压力,需要对接口调用次数限制,...

  • laravel HTTPException 429 Too M

    Laravel 5.2 引入的 throttle middleware 作用是实现接口访问频率限制的 默认一分钟限...

  • Lumen访问频率限制

    在App\Http\Middleware下新建文件RateLimits.php写入内容 在app.php中rout...

  • Django:rest framework之限流(throttl

    一 什么是throttle 简介:Django restframework的throttle可以对接口访问的频次进...

  • 用lumen写接口犯了一个严重的错误

    1.我在用lumen写接口后,在本地用ajax跨域访问,发现ajax没有用,再看过大神用lumen写的接口发现,我...

  • 限制接口访问频率

    限流,就是限制对 API 的调用频率。每一次 API 调用,都要花费服务器的资源,因此很多 API 不会对用户无限...

  • Redis 实现接口访问频率限制

    为什么限制访问频率 做服务接口时通常需要用到请求频率限制 Rate limiting,例如限制一个用户1分钟内最多...

  • 构建API服务器4

    限制API调用频率 使用redis-throttle 集成到Rails中,修改config/application...

  • 函数防抖与函数节流

    debounce -- 函数防抖,throttle -- 函数节流都是在JavaScript中可以限制函数发生频率...

  • 节流

    节流(throttle) 节流函数:只允许一个函数在N秒内执行一次。滚动条调用接口时,可以用节流throttle等...

网友评论

    本文标题:lumen接口访问频率throttle

    本文链接:https://www.haomeiwen.com/subject/krmlpqtx.html