[英]How to set the rate limiter for per second in Laravel version 8
如何在Laravel 中设置每秒速率限制器 8 。 我需要每秒而不是每分钟设置速率限制器。
速率限制器 (Laravel 8) - https://laravel.com/docs/8.x/routing#rate-limiting
现在我可以在几分钟、几小时等时间内使用 Laravel 的速率限制器。但我正在尝试实现一秒钟的速率限制器。 我想限制每秒 25 个请求。 (从“Illuminate\Cache\RateLimiting\Limit”导出限制 class)
请检查我使用的以下代码
RateLimiter::for('api', function (Request $request) {
return [
// Rate limiter based on Client IP Address
Limit::perMinute(env('IP_ADDR_RATE_LIMITER_PER_MINUTE', 60))->by($request->ip())->response(function () {
....
}),
// Rate limiter based on API key/User
Limit::perMinute(env('API_KEY_RATE_LIMITER_PER_MINUTE', 60))->by($request->input('key'))->response(function () {
...
})
];
});
有没有办法限制每秒 25 个请求?
注意:还尝试在 Illuminate\Cache\RateLimiting\Limit 中添加/更改函数,我尝试在其中更改每分钟 function。提前致谢。
可以配置 Laravel 8 RateLimitter 以允许 req/seconds
这是您正在寻找的示例: https : //learn2torials.com/thread/how-to-set-the-rate-limiter-for-per-second-in-laravel-version-8
<?php
namespace App\Http\Cache;
class Limit extends \Illuminate\Cache\RateLimiting\Limit
{
/**
* Create a new limit instance.
*
* @param mixed|string $key
* @param int $maxAttempts
* @param int|float $decayMinutes
* @return void
*/
public function __construct($key = '', int $maxAttempts = 60, $decayMinutes = 1)
{
$this->key = $key;
$this->maxAttempts = $maxAttempts;
$this->decayMinutes = $decayMinutes;
}
/**
* Create a new rate limit using seconds as decay time.
*
* @param int $decaySeconds
* @param int $maxAttempts
* @return static
*/
public static function perSeconds($decaySeconds, $maxAttempts)
{
return new static('', $maxAttempts, $decaySeconds/60.0);
}
}
您可以重新定义 Limit 类
通过第四个 position 的最大秒数
$executed = RateLimiter::attempt(
'send-message:'.$user->id,
$perMinute = 5,
function() {
// Send message...
}, 1 // this would be one second
);
这将是每秒 5 次尝试
1- 在RouteServiceProvider
中配置速率限制器
2- 打开App\Providers\RouteServiceProvider::class
并添加以下更改:
/** *
Configure the rate limiters for the application.
*
*
@return void
*/
protected function configureRateLimiting()
{
// ALLOW 1500/60 = 25 Request/Sec
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(1500); });
// ALLOW 1000/60 = 16.66 Request/Sec
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(1000)->response(function () {
return response('Too many request...', 429);
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.