laravel 5.6 API 接口开发限制接口访问频率
在laravel 5.6及以上版本中框架中已自带ThrottleRequests,但是为了更好的处理消息,我们可以再新加一个中间件,来更方便的处理相应信息
第一步: php artisan make:middleware ThrottleRequests
在ThrottleRequest类中放入以下代码
namespace App\Http\Middleware; use Closure;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response; class ThrottleRequests
{
/**
* The rate limiter instance.
*
* @var \Illuminate\Cache\RateLimiter
*/
protected $limiter; /**
* Create a new request throttler.
*
* @param \Illuminate\Cache\RateLimiter $limiter
*/
public function __construct(RateLimiter $limiter)
{
$this->limiter = $limiter;
} /**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $maxAttempts 最大请求次数
* @param int $decayMinutes 时间,分为单位
* @return mixed
*/
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request); if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
return $this->buildResponse($key, $maxAttempts);
} $this->limiter->hit($key, $decayMinutes); $response = $next($request); return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
} /**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function resolveRequestSignature($request)
{
return $request->fingerprint();
} /**
* Create a 'too many attempts' response.
*
* @param string $key
* @param int $maxAttempts
* @return \Illuminate\Http\Response
*/
protected function buildResponse($key, $maxAttempts)
{
$message = json_encode([
'data' => [
'messsage' => '请求次数太多' //may comes from lang file
,'code' => 429, //your custom code
'data'=>''
] ]); $response = new Response($message, 429); $retryAfter = $this->limiter->availableIn($key); return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
$retryAfter
);
} /**
* Add the limit header information to the given response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
* @return \Illuminate\Http\Response
*/
protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
{
$headers = [
'X-RateLimit-Limit' => $maxAttempts,
'X-RateLimit-Remaining' => $remainingAttempts,
]; if (!is_null($retryAfter)) {
$headers['Retry-After'] = $retryAfter;
$headers['Content-Type'] = 'application/json';
} $response->headers->add($headers); return $response;
} /**
* Calculate the number of remaining attempts.
*
* @param string $key
* @param int $maxAttempts
* @param int|null $retryAfter
* @return int
*/
protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null)
{
if (!is_null($retryAfter)) {
return 0;
} return $this->limiter->retriesLeft($key, $maxAttempts);
}
}
使用:
使用,可以在api.php 路由中这样使用
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->group(['middleware'=>'throttle:3,1'] , function ($api) {
其中3表示请求次数,1为分钟。以上设置为每分钟只能请求3 次
或者在Kernel.php $middlewareGroups中配置 'api' => [
'throttle:3,1',
'bindings',
],



laravel 5.6 API 接口开发限制接口访问频率的更多相关文章
- 基于Axis1.4的webservice接口开发(接口调用)
基于Axis1.4的webservice接口开发(接口调用) 一.webservice接口代码参考上一篇博客: http://www.cnblogs.com/zhukunqiang/p/7125668 ...
- 接口开发-集成接口文档(swagger)
在正式进入主题之前,先说说实际工作中遇到的问题.不算是传统的原生APP开发,还是眼下的H5混合开发,只要是需要前后端通过接口配合的,往往都存在几个普遍的问题 (1)接口文档谁来写,尤其是跨部门,并且, ...
- 用ASP.NET Web API技术开发HTTP接口
开发工具 Visual Studio 2013 SQL Server 2008 R2 准备工作 启动Visual Studio 2013,新建一个ASP.NET Web应用程序,命名为SimpleAP ...
- 用ASP.NET Web API技术开发HTTP接口(一)
开发工具 Visual Studio 2013 SQL Server 2008 R2 准备工作 启动Visual Studio 2013,新建一个ASP.NET Web应用程序,命名为SimpleAP ...
- 用ASP.NET Web API技术开发HTTP接口(二)
在第一部分,我们创建了一个基本的ASP.NET Web API项目,新建成功了数据表,然后添加了一些测试数据,最后创建了API控制器,用json格式把数据表里面的内容成功输出到浏览器上.接下来我们将继 ...
- 接口开发01--mock接口
开发接口的常见场景: 1.mock接口,模拟一些接口,在别的接口没有开发好的时候,你需要测试,可以先模拟一个假接口来测试.比如常见 2.若需要调用第三方接口时,比如支付接口. 3.查看数据,比如开放数 ...
- FastAPI(六十六)实战开发《在线课程学习系统》接口开发--用户注册接口开发
在前面我们分析了接口的设计,那么我们现在做接口的开发. 我们先去设计下pydantic用户参数的校验 from pydantic import BaseModel from typing import ...
- 在线支付接口之PHP支付宝接口开发简单介绍
php100:92:在线支付接口之PHP支付宝接口开发 支付接口一般是第三方提供的代收款.付款的平台,可以通过支付接口帮助企业或个人利用一切可以使用的支付方式.常见支付平台:支付宝.快钱.云网支付.财 ...
- 基于Axis1.4的webservice接口开发(代码开发)
基于Axis1.4的webservice接口开发(代码开发) 一.开发环境: 我的开发环境是MyEclipse 2015+Apache-Tomcat-8.0.21. 二.代码开发: 1.新建一个Web ...
随机推荐
- winSCP上传文件到服务器失败,提示permission denied,返回码3
1.查看sftp服务在你服务器的路径 cat /etc/ssh/sshd_config | grep sftp 2.在winSCP进行连接设置 设置好你的主机名.端口.用户名和密码,然后点击高级,点击 ...
- position和anchorPoint笔记
position和anchorPoint是CAlayer的两个属性. 我们以前修改一个控件的位置都是能过Frame的方式进行修改. 现在利用CALayer的position和ancho ...
- 有了Autolayout的UILabel
在没有Autolayout之前,UILabel的文字内容总是居中显示,导致顶部和底部会有一大片空缺区域 有Autolayout之后,UILabel的bounds默认会自动包住所有的文字内容,顶部和底部 ...
- linux下打包所有文件,包括隐藏文件到压缩包
命令如下: cd /root/test/ tar czvf test.tar.gz .[!.]* * 解释: tar czvf test.tar.gz * 压缩当前文件夹下非[隐藏文件]的文件 tar ...
- 【转载收藏】使用Jacoco远程统计tomcat服务的代码覆盖率
在做软件开发的时候经常会遇到做各种测试,这里介绍一种本人遇到的:代码覆盖率测试, 这个测试非常实用,能发现许多无效的模块和代码.强烈推荐!!!!! 网上好多资料都不全,而且没有详细的配置流程 本文将简 ...
- 使用Reachability监测网络变化-陈鹏
在appdelegate里面添加观察者,并启动监测 // 使用通知中心监听kReachabilityChangedNotification通知 [[NSNotificationCenter defau ...
- 你还不懂java的日志系统吗
一.背景 在java的开发中,使用最多也绕不过去的一个话题就是日志,在程序中除了业务代码外,使用最多的就是打印日志.经常听到的这样一句话就是"打个日志调试下",没错在日常的开发.调 ...
- Python支付宝单笔转账接口
开发信息 接口加签方式为证书模式 证书模式好处是可以使用支付宝的转账到支付宝账户,也就是提现功能,公钥模式不能实现转账到支付宝账户. 此DEMO利用单笔转账到支付宝账户接口[提现功能]用户可以通过此D ...
- MySql索引分析及查询优化
B-Tree 核心特点: 多路,非二叉树 每个节点既保存索引,又保存数据 搜索时相当于二分查找 B+Tree 核心特点 多路非二叉 只有叶子节点保存数据 搜索时相当于二分查找 增加了相邻接点的指向指针 ...
- Solution -「AGC 012F」「AT 2366」Prefix Median
\(\mathcal{Description}\) Link. 给定序列 \(\{a_{2n-1}\}\),将 \(\{a_{2n-1}\}\) 按任意顺序排列后,令序列 \(b_i\) 为前 ...