我刚刚创建了自己的缓存适配器,允许通过模式获取缓存项,它使用 redisSCAN
指令:
use Symfony\Component\Cache\Traits\{
RedisProxy, RedisTrait
};
use Symfony\Component\Cache\Adapter\AbstractAdapter;
use Generator;
/**
* Class RedisAdapter
* Advanced redis adapter with the ability to fetch items using expressions
* @package App\Cache
*/
class RedisAdapter extends AbstractAdapter
{
use RedisTrait;
/**
* @var RedisProxy
*/
private $redis;
/**
* @var string
*/
private $namespace;
/**
* @var int
*/
private $namespaceLen;
public function __construct($redisClient, string $namespace = '', int $defaultLifetime = 0)
{
$this->init($redisClient, $namespace, $defaultLifetime);
$this->namespace = $namespace . ':';
$this->namespaceLen = strlen($this->namespace);
}
/**
* Get all cache items by pattern
* @param string $pattern
* @return Generator
*/
public function getItemsByPattern(string $pattern): Generator
{
$iterator = null;
$pattern = $this->prependNamespace($pattern);
while ($keys = $this->redis->scan($iterator, $pattern)) {
foreach ($this->getItems($this->cleanupNamespace($keys)) as $item) {
yield $item;
}
}
}
/**
* Add a namespace to the key
* @param string $key
* @return string
*/
private function prependNamespace(string $key): string
{
return $this->namespace . $key;
}
/**
* Cleanup the namespace
* @param array $keys
* @return array
*/
private function cleanupNamespace(array $keys)
{
$keys = array_map(function ($value) {
return substr($value, $this->namespaceLen);
}, $keys);
return $keys;
}
}