在这里,您需要共享计时器,例如控制传出请求的频率上限。创建一个类,它将成为 Laravel 应用程序的单例,并且可以在请求中共享。
class FrequencyCapper{
protected $start, $call, $request_frequency, $limit_interval;
public function __construct($frequency, $interval_in_minute){
$this->start = time();
$this->call = 0;
$this->request_frequency = frequency; // frequency of call
$this->limit_interval = $interval_in_minute; // in minutes
}
protected function allowRequest(){
$diff = time() - $this->start;
if($diff >= 60 * $this->limit_interval){
$this->start = time();
$this->call = 0;
}
return $diff < 60 * $this->limit_interval && $this->call < $this->request_frequency){
$this->call++;
return true;
}else{
return false;
}
}
}
现在,将这个类作为一个单例附加到 laravel 服务容器中。App\Providers\AppServiceProvider.php
在's boot 方法中绑定单例。
$this->app->singleton('FrequencyCapper', function ($app) {
return new FrequencyCapper(25, 1); //max 25 request per minute
});
现在,这个类将作为依赖项提供给所有控制器。您可以将依赖项注入FrequencyCapper
给定的任何控制器方法,
class MyController extends Controller{
protected function sendRequest(FrequencyCapper $capper){
if($capper->allowRequest()){
//you can call the api
}
}
}
如果你愿意,你可以在课堂上使用microtime()
time() 。FrequencyCapper
如果你想限制传入的请求到你自己的 api,你可以使用 laravel 的throttle
中间件,
Route::group(['prefix' => 'api', 'middleware' => 'throttle:25,1'], function(){
//define your routes here
});