在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 接口开发限制接口访问频率的更多相关文章

  1. 基于Axis1.4的webservice接口开发(接口调用)

    基于Axis1.4的webservice接口开发(接口调用) 一.webservice接口代码参考上一篇博客: http://www.cnblogs.com/zhukunqiang/p/7125668 ...

  2. 接口开发-集成接口文档(swagger)

    在正式进入主题之前,先说说实际工作中遇到的问题.不算是传统的原生APP开发,还是眼下的H5混合开发,只要是需要前后端通过接口配合的,往往都存在几个普遍的问题 (1)接口文档谁来写,尤其是跨部门,并且, ...

  3. 用ASP.NET Web API技术开发HTTP接口

    开发工具 Visual Studio 2013 SQL Server 2008 R2 准备工作 启动Visual Studio 2013,新建一个ASP.NET Web应用程序,命名为SimpleAP ...

  4. 用ASP.NET Web API技术开发HTTP接口(一)

    开发工具 Visual Studio 2013 SQL Server 2008 R2 准备工作 启动Visual Studio 2013,新建一个ASP.NET Web应用程序,命名为SimpleAP ...

  5. 用ASP.NET Web API技术开发HTTP接口(二)

    在第一部分,我们创建了一个基本的ASP.NET Web API项目,新建成功了数据表,然后添加了一些测试数据,最后创建了API控制器,用json格式把数据表里面的内容成功输出到浏览器上.接下来我们将继 ...

  6. 接口开发01--mock接口

    开发接口的常见场景: 1.mock接口,模拟一些接口,在别的接口没有开发好的时候,你需要测试,可以先模拟一个假接口来测试.比如常见 2.若需要调用第三方接口时,比如支付接口. 3.查看数据,比如开放数 ...

  7. FastAPI(六十六)实战开发《在线课程学习系统》接口开发--用户注册接口开发

    在前面我们分析了接口的设计,那么我们现在做接口的开发. 我们先去设计下pydantic用户参数的校验 from pydantic import BaseModel from typing import ...

  8. 在线支付接口之PHP支付宝接口开发简单介绍

    php100:92:在线支付接口之PHP支付宝接口开发 支付接口一般是第三方提供的代收款.付款的平台,可以通过支付接口帮助企业或个人利用一切可以使用的支付方式.常见支付平台:支付宝.快钱.云网支付.财 ...

  9. 基于Axis1.4的webservice接口开发(代码开发)

    基于Axis1.4的webservice接口开发(代码开发) 一.开发环境: 我的开发环境是MyEclipse 2015+Apache-Tomcat-8.0.21. 二.代码开发: 1.新建一个Web ...

随机推荐

  1. echarts图表的封装

    其实echarts官网有个快速上手的教程,一般人看一遍也知道是怎么回事,先给个传送门吧--五分钟上手 引入方式多种多样就自己去官网看了--这里简单介绍echarts怎么用,下方的封装函数比较重要 1. ...

  2. jsp 九大内置对象和其作用以及四大域对象

    感谢作者:Fangcf. 链接:https://blog.csdn.net/qq_39320833/article/details/80818442 一.jsp 九大内置对象 方法简单介绍:https ...

  3. C语言中的typedef跟define的区别

    今天用C语言练习时涉及到了typedef和define的使用问题,那么他们的区别是啥?这种情况下为什么要用typedef?哪种情况下为什么要用define呢? 学习C的时候的你是否考虑过这个问题呢? ...

  4. java多线程编程(二)

    1. wait 和 sleep 区别? 1.wait可以指定时间也可以不指定,sleep必须指定时间. 2.在同步中时,对cpu的执行权和锁的处理不同.  wait:释放执行权,释放锁.  sleep ...

  5. shell脚本命令(sotr/unip/tr/cut/eval)与正则表达式

    shell脚本命令(sotr/unip/tr/cut/eval)与正则表达式 1.sort命令 概述: Linux sort命令用于将文本文件内容加以排序. sort命令可针对文本文件的内容,以行为单 ...

  6. 【CF457D】Bingo!(数学 期望)

    题目链接 大意 给定\(N,M,K\),表示有一个\(N*N\)的空矩阵,\(M\)个不同的数. 随机地把\(M\)个数中的\(N^2\)个数丢进这个空矩阵中(\(M\ge N^2\)) 再从\(M\ ...

  7. Node介绍

    https://segmentfault.com/a/1190000006121183 一. 概述 Node.js是基于Chrome JavaScript运行时建立的一个平台,实际上它是对Google ...

  8. Linux系统安装(CentOS-7)详细操作步骤

    Linux系统安装(CentOS-7)详细操作步骤 一.创建虚拟机 首先创建一个虚拟机,然后才能在虚拟机里面安装系统. 第一步,创建虚拟机的向导 第二步,兼容性默认即可. 第三步,我们等创建完虚拟机后 ...

  9. head 插件 Content-Type header [application/x-www-form-urlencoded] is not supported

    { "error": "Content-Type header [application/x-www-form-urlencoded] is not supported& ...

  10. ESXI 7.0.0 U2 部署

    文章目录 什么是ESXI? ESXi 的优势 功能特性 部署ESXI 创建虚拟机 开始安装 打开浏览器输入ip进行管理 什么是ESXI? ESXI官网:https://www.vmware.com/c ...