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 ...
随机推荐
- JoJoGAN 实践
JoJoGAN: One Shot Face Stylization. 只用一张人脸图片,就能学习其风格,然后迁移到其他图片.训练时长只用 1~2 min 即可. code paper 效果: 主流程 ...
- Ajax向服务器发起请求
Ajax向服务器发起请求的三个步骤: 1:创建Ajax 2:打开Ajax,打开Ajax请求 3:向服务器发起请求:需要知道地址和是get请求还是post方法 向服务器发起请求的两个方法:open 和 ...
- Linux下Mysql端口修改及防火墙开端口
用户权限问题:https://blog.csdn.net/weixin_43670802/article/details/103019598 Linux下修改Mysql默认的3306端口 如下: 1. ...
- 深入分析Java中的关键字static
在平时开发当中,我们经常会遇见static关键字.这篇文章就把java中static关键字的使用方法的原理进行一个深入的分析.先给出这篇文章的大致脉络: 首先,描述了static关键字去修饰java类 ...
- 从上下文中获取所有的原生controller
1 /** 2 * 获取项目所有被注解修饰的url 3 * @param run 4 */ 5 public void getAllUrl(ConfigurableApplicationContext ...
- 程序员的情人节「GitHub 热点速览 v.22.07」
又是一年情人日,刚好还是发文的今天.也没什么好送的,送点程序员的浪漫--代码和开源项目吧.记得在本周特推查收这份来自程序员的独有浪漫. 本周 GitHub 霸榜的项目基本上都是老项目,从老项目中挖点新 ...
- Java面试-常见基础笔试题目
1. Vector, ArrayList, LinkedList的区别 Vector:①长度可变,以类似数组的形式存储于内存中,线程安全(同步),因为其大部分方法都有synchronized 关键字, ...
- 聊一聊Redis事务
没错,Redis也有事务管理,但是功能很简单,在正式开发中也并不推荐使用.但是面试中有可能会问到,所以本文简单谈一谈Redis的事务. 通过这篇文章,你会了解 Redis为什么要提供事务? Redis ...
- Memory Management in Rust
程序在运行时需要请求操作系统分配内存以及释放内存,因此,程序员在编写程序时,需要显式(手动)地编写分配和释放内存的代码,或者隐式(自动,由语言保证)地进行内存管理.对于前者,C/C++ 是代表语言,程 ...
- 打造一款属于自己的CentOS操作系统
文章目录 声明 关闭selinux以及firewalld 修改终端前缀显示 修改默认网卡名称为eth0 替换yum源 安装常用工具 优化history 配置回收站 迎宾显示 优化vim 清空yum缓存 ...