在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. 关于https域名下的页面iframe嵌套http页面的问题

    业务场景:在一个https域名下用iframe嵌套一个http域名的页面,会直接报错的,报错信息如下: 这段话的意思是:http域名的页面是通过https域名页面加载的,在一个安全的页面不允许加载一个 ...

  2. VMware网络连接模式(桥接、NAT以及仅主机模式的详细介绍和区别)

    VMware 桥接模式 VMware桥接模式,也就是将虚拟机的虚拟网络适配器与主机的物理网络适配器进行交接,虚拟机中的虚拟网络适配器可通过主机中的物理网络适配器直接访问到外部网络(例如图中所示的局域网 ...

  3. windows平台编码转换

    int AsciiToUtf8(char* pSrc, unsigned int nSrcLen, char* pBuffer, unsigned int nBufferLen) { assert(p ...

  4. java getSource()和 getActionCommand()区别

    感谢大佬:https://blog.csdn.net/LIU_YANZHAO/article/details/72740011?utm_source=blogxgwz1 比如说 按纽的事件,同一个JF ...

  5. Nginx http重定向https

    SSL证书申请的腾讯的,配置好证书后,直接监听80端口转发443就ok了 转发语句:rewrite ^/(.*) https://$server_name:443$request_uri? perma ...

  6. 【转】Nginx location写法

    转自:https://www.cnblogs.com/IPYQ/p/7889399.html nginx location正则写法 location = / { # 精确匹配 / ,主机名后面不能带任 ...

  7. DNS域名解析之反向解析and主从域名服务器 (今天大小便正常,未来可期)

    DNS解析之反向解析和域名主从服务器 反向解析:根据IP地址查找对应的域名 yum -y install bind 安装软件包 查看需要修改的配置文件所在路径 rpm -qc bind 查询bind软 ...

  8. 蟒蛇书学习笔记——Chapter 09 Section 01 创建和使用类

    9.1 创建和使用类 9.1.1 创建Dog类   根据Dog类创建的每个实例都将存储名字和年龄,我们赋予了每条小狗蹲下(sit( ))和打滚(roll_over( ))的能力: class Dog: ...

  9. Node介绍

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

  10. 初探Matrix Android ApkChecker

    背景 因为我所在的项目是做投放包,对安卓包的大小很敏感,经常会优化包的大小,所以想引入工具静态检测包大小,看能不能找到其中可以优化的地方,防患于未然.Matrix是微信终端自研和正在使用的一套APM( ...