-
Hello, This issue should be considered as a question, not a bug or something else. :-) I had to implement and use RateLimiterStore because i need to share the RateLimiterStore between different Symfony custom Command that could run during the same time. For that i developed this using Symfony 5.2.1: <?php
namespace App\Store;
use Psr\Cache\InvalidArgumentException;
use Spatie\GuzzleRateLimiterMiddleware\Store;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\CacheItem;
use Symfony\Contracts\Cache\ItemInterface;
class RateLimiterStore implements Store
{
/**
* @var FilesystemAdapter $cache
*/
private $cache;
/**
* @var string $itemKey
*/
private $itemKey;
/**
* RateLimiterStore constructor.
* @param FilesystemAdapter $cache
* @param string $itemKey
*/
public function __construct(FilesystemAdapter $cache, string $itemKey)
{
$this->cache = $cache;
$this->itemKey = $itemKey;
}
public function get(): array
{
try {
return $this->cache->get($this->itemKey, function (ItemInterface $item) {
return [];
});
} catch (InvalidArgumentException $e) {
}
}
public function push(int $timestamp, int $limit)
{
try {
/**
* @var CacheItem $cacheItem
*/
$cacheItem = $this->cache->getItem($this->itemKey);
$cacheItem->set(array_merge($this->get(), [$timestamp]));
$this->cache->save($cacheItem);
} catch (InvalidArgumentException $e) {
}
}
/**
* Clear all cache used by RateLimiterStore
*/
public function clear()
{
$this->cache->clear();
}
} As you can see, i am using FilesystemAdapter because i do not have any Redis, Memcache or APCu on my server. Also, I implemented a public function "clear", this public function is used by another Symfony custom Command whose role is to clear the cache. In fact, i plan to execute this custom Command hourly to ensure that the cache is not growing too much (for performances reasons). Based on my tests, seems this implementation is working. But i would like your advice on it. Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
IMHO, you could change the signature of your
Why don't use Redis? Because you're on a shared hosting or other reason? Redis, Memcache, APCu are (for me & for this case) the best way to cache data with TTL. They will automatically flush data when keys expired and they are accessed over a network.
That's a correct behaviour because FS cache isn't cleaning itself automatically. 😞 |
Beta Was this translation helpful? Give feedback.
IMHO, you could change the signature of your
RateLimiterScore
fromFilesystemAdapter $cache
toCacheItemPoolInterface $cache
for interoperability (refs to PSR-6).Today you're using FS cache, but who knows if tomorrow you'll use another cache system instead?
Why don't use Redis? Because you're on a shared hosting or other reason?
Redis, Memcache, APCu are (for me & for this case) the best way to cache data with TTL. They will automatically flush data when keys expired and they are accessed over a network.