限制接口的访问次数_Lumen 使用 throttle 限制接口访问频率

本文介绍了在 Lumen 框架中如何实现接口访问限制,通过自定义和使用 `ThrottleRequests` 中间件,限制用户在2分钟内访问特定接口不超过10次,防止恶意请求或频繁操作。
摘要由CSDN通过智能技术生成

前言

今天碰到过这样一个情况,我需要限制用户请求某个API接口的频率,比如登录、反馈等提交操作,经过一番搜索+折腾,总算是实现了。

Laravel 5.2的新特性中增加了一个 throttle中间件,通过它可以在路由层限制 API访问的频率。例如限制频率为1分钟50次,如果一分钟内超过了这个限制,它就会响应:429: Too Many Attempts。

但我在项目中使用的是Lumen框架(它只有Laravel中的一部分功能),它并没有集成这个中间件,所以本文主要是讲述如何在Lumen框架中加入throttle中间件。

开始

首先我们要在appHttpMiddleware中新建ThrottleRequests.php文件。

并且把以下链接中的代码拷贝到这个文件中:

https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php

接着修改文件中的命名空间:

namespace AppHttpMiddleware;

标记同一用户端请求

因为Lumen框架缺失部分功能,我们需要修改ThrottleRequests.php中的resolveRequestSignature方法:

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

抛出响应

throttle超过限制时抛出的是IlluminateHttpExceptionsThrottleRequestsException,同样Lumen框架缺少这个文件,需要自己定义一下,在app/Exceptions中新建ThrottleException.php,写入以下代码:

<?php

namespace AppExceptions;

use Exception;

class ThrottleException extends Exception{
    protected $isReport = false;

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

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

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

修改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.', 429);
}
需在文件头部中添加这一行: use AppExceptionsThrottleException;

注册中间件

bootstrap/app.php中注册:

$app->routeMiddleware([
     'throttle' => AppHttpMiddlewareThrottleRequests::class,
]);

到这里我们就加入成功了,接着在路由中添加中间件即可:

$router->group(['middleware' => ['throttle:10,2']],function() use ($router){

    $router->post('feedback','UserController@addFeedback');

});

其中throttle:10,2表示的是2分钟内访问10次。

注:此文为原创文章,如需转载,请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值