我正在将我的应用连接到仅允许同时进行2次API调用的API。
如何从我的应用程序中限制它?如果通过我的应用程序生成了两个以上的并发API请求,则我想对此进行限制。
我可以通过在表中设置一个标志来做到这一点,但是我想知道的是,有一种更聪明的laravel方法来做到这一点吗?
Laravel版本5.4。
您需要在多个进程之间共享活动API调用的数量。
您可以为此目的将共享内存与信号灯结合使用。
[您可以使用多种选项来使用共享内存,即:shmop,shm,apc您可以使用sem_acquire / sem_release限制对共享内存的同时访问。
因此,您可以使用几个函数来排队API调用:
function aquire_permission_for_api_call(){
$sem = sem_get("api_call_manager");
$ok=false;
do {
sem_aquire($sem);
$active_calls_storage = shm_attach("api_call_manager_storage");
$number_of_active_calls = shm_get_var($active_calls_storage,0);
if($number_of_active_calls<2){
$number_of_active_calls++;
$ok=true;
shm_put_var($active_calls_storage,0, number_of_active_calls);
}
sem_release($sem);
}while(!$ok);
}
function report_completion_of_api_call(){
$sem = sem_get("api_call_manager");
$ok=false;
sem_aquire($sem);
$active_calls_storage = shm_attach("api_call_manager_storage");
$number_of_active_calls = shm_get_var($active_calls_storage,0);
$number_of_active_calls-;
shm_put_var($active_calls_storage,0, number_of_active_calls);
sem_release($sem);
}
然后您可以像这样使用它:
aquire_permission_for_api_call();
$response = $client->make_api_call();
report_completion_of_api_call();
PS:我没有测试此代码。我希望你有个主意。