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 ...
随机推荐
- 一个label 混搭不同颜色,不同字体的文字.. by 徐
效果如图箭头所示,只需要一个label就可以做到不同颜色或不同字体的效果 1 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, ...
- 安装Linux8.3.2011
镜像地址:http://mirrors.aliyun.com/centos/8.3.2011/isos/x86_64/ 非DVD镜像安装时的安装源地址:http://mirrors.aliyun.co ...
- Java中的equals和==的区别以及几个常用的object中的方法简单的调试方法
一.equals 1.equals:是Object类中的方法,只能判断引用类型 2.默认判断的是地址是否相等(判断两个参数是否是同一个对象),子类中往往重写该方法,用于判断内容(值)是否相等 二.== ...
- 用Java中的File类模拟实现对系统文件的增删改查效果
码字不易,三连支持一波吧 IO操作向来是各大语言的热区,而对文件的操作也是重中之重. 那么在Java中也给我们提供了很多关于文件操作的类.今天我就用一个比较基本的File类来模拟实现对文件的增删改查效 ...
- DelayQueue延迟队列-实现缓存
延迟阻塞队列DelayQueue DelayQueue 是一个支持延时获取元素的阻塞队列, 内部采用优先队列 PriorityQueue 存储元素, 同时元素必须实现 Delayed 接口:在创建元素 ...
- Ubuntu20.04.3中telnet 127.0.0.1时Unable to connect to remote host: Connection refused
本博客旨在自我学习使用,如有任何疑问请及时联系博主 今天遇到个稀奇古怪的问题: 调试emqx的时候一直econnrefused,检查服务时,突然发现在ubuntu上telnet localhost竟然 ...
- Solution -「HEOI/TJOI 2016」「洛谷 P2824」排序
\(\mathcal{Description}\) Link. 给定排列 \(\{p_n\}\) 和 \(m\) 次局部排序操作,求操作完成后第 \(q\) 位的值. \(n,m\le10 ...
- C#设置进程PATH环境变量值解决某些Win32DLL找不到路径问题
C#.NET通过设置当前进程PATH环境变量值解决某些Win32DLL找不到路径问题 以下函数设置PATH环境变量值(请注意:该环境变量为当前进程的环境变量,非系统环境变量)用于解决在调用某些Win3 ...
- [LeetCode]26.删除有序数组中的重复项(Java)
原题地址: remove-duplicates-from-sorted-array 题目描述: 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的 ...
- 图片隐写之Image Steganography软件的使用
CTF_论剑场 MISC 坏掉的图像 writeup 把图片丢进winhex里,发现头部的 0D 1A 0A 1A是不正确的,正确的应该为 0D 0A 1A 0A,所以需要更改. 更改完成后打开图片可 ...