【问题标题】:Laravel - Restrict only upto 2 API callsLaravel - 最多限制 2 个 API 调用
【发布时间】:2020-03-19 18:37:40
【问题描述】:

我正在将我的应用程序连接到一个只允许同时调用 2 个 API 的 API。

如何从我的应用程序中限制它?如果通过我的应用程序生成超过 2 个并发 API 请求,我想对此进行限制。

我可以通过在表中设置一个标志来做到这一点,但我想知道的是,有没有更聪明的 laravel 方式来做到这一点?

Laravel 版本 5.4。

【问题讨论】:

  • 您想要 2 个并发用户还是 2 个并发 API 请求?两者都太不一样了。
  • 2 个并发请求。我已经编辑了问题
  • 我的要求是用户独立的。许多用户可能同时访问应用程序,但总共只允许 2 个 API 调用

标签: php laravel-5 php-7


【解决方案1】:

您需要跨多个进程共享活动 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");
    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:我没有测试这段代码。我希望你有一个想法。

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2022-07-21
    • 2022-01-01
    • 2019-04-28
    • 2015-02-25
    • 2012-02-01
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多