Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rate Limit Subscriber for Guzzle 4.x + Laravel
<?php
/**
* Todo: Decouple from Laravel's Caching system
**/
use GuzzleHttp\Collection;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\EmitterInterface;
use GuzzleHttp\Event\SubscriberInterface;
class RateLimitSubscriber implements SubscriberInterface
{
/** @var Collection Configuration settings */
private $config;
public function __construct(array $config = [])
{
$this->config = Collection::fromConfig($config, [
'msBetweenRequests' => '1000',
]);
}
public function getEvents()
{
return [
'before' => ['onBefore'],
'complete' => ['onComplete'],
];
}
public function onBefore(BeforeEvent $event)
{
$ms = $this->config['msBetweenRequests'] * 1000;
if ($time = \Cache::get('guzzleRateLimit.'.$this->getKey($event)) ) {
$elapsed = microtime(true) - $time;
if ($elapsed < $ms) {
usleep($ms - $elapsed);
}
}
}
public function onComplete(CompleteEvent $event)
{
\Cache::forever('guzzleRateLimit.'.$this->getKey($event), microtime(true));
}
protected function getKey($event)
{
return $event->getRequest()->getHost();
}
}
@younes0

This comment has been minimized.

Copy link
Owner Author

@younes0 younes0 commented Aug 4, 2014

Usage:

$client->getEmitter()->attach(new RateLimitSubscriber([
    'msBetweenRequests' => 2000,
]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment