本文介绍了速率限制传出 PHP+curl 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制(延迟)传出到外部服务器的 PHP+curl 请求,以便每秒只有 n 个请求?PHP 在 Fastcgi 模式下使用,因此无法使用睡眠.

Is there a way to rate limit (with delay) outgoing PHP+curl requests to an external server, so that there are only n requests per second? PHP is used in Fastcgi mode so not possible to use sleep.

推荐答案

您可以使用 令牌控制费率桶算法.由于您想控制一种资源的所有 PHP 进程的速率,因此您需要共享存储桶的状态.您可以使用我的实现以线程安全的方式执行此操作:bandwidth-throttle/token-bucket

You can control the rate with the token bucket algorithm. As you want to control the rate of all your PHP processes for one resource you will need to share the state of the bucket. You can do this in a threadsafe way with my implementation: bandwidth-throttle/token-bucket

use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\BlockingConsumer;
use bandwidthThrottle\tokenBucket\storage\FileStorage;

$storage  = new FileStorage(__DIR__ . "/api.bucket");
$rate     = new Rate(10, Rate::SECOND);
$bucket   = new TokenBucket(10, $rate, $storage);
$consumer = new BlockingConsumer($bucket);
$bucket->bootstrap(10);

// This blocks all processes to the rate of 10 requests/second
$consumer->consume(1);

$api->doSomething();

这篇关于速率限制传出 PHP+curl 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:57