Класс RedisAdapter
Класс RedisAdapter является адаптером
кэша и сохраняет элементы в Redis. Первым
параметром передаётся клиент Redis или DSN
для подключения, вторым - пространство имён
ключей. Адаптер реализует интерфейс
AdapterInterface и работает через
CacheItemPoolInterface.
Синтаксис
new RedisAdapter($redis, $namespace, $defaultLifetime)
Пример
Давайте создадим адаптер и сохраним в кэш строку:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentCacheAdapterRedisAdapter;
use SymfonyComponentRoutingAttributeRoute;
class CacheController extends AbstractController
{
#[Route('/cache', name: 'cache_index')]
public function index(): Response
{
$redis = new RedisAdapter(
new \Redis(),
'app'
);
$item = $redis->getItem('key_1');
$item->set('hello');
$redis->save($item);
return new Response('saved');
}
}
?>
Результат выполнения кода:
saved
Пример
Давайте прочитаем значение из кэша:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentCacheAdapterRedisAdapter;
use SymfonyComponentRoutingAttributeRoute;
class CacheController extends AbstractController
{
#[Route('/cache/read', name: 'cache_read')]
public function read(): Response
{
$redis = new RedisAdapter(
new \Redis(),
'app'
);
$item = $redis->getItem('key_1');
return new Response($item->get());
}
}
?>
Результат выполнения кода:
hello
Пример
Давайте зададим время жизни элемента через
expiresAfter:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentCacheAdapterRedisAdapter;
use SymfonyComponentRoutingAttributeRoute;
class CacheController extends AbstractController
{
#[Route('/cache/ttl', name: 'cache_ttl')]
public function ttl(): Response
{
$redis = new RedisAdapter(
new \Redis(),
'app'
);
$item = $redis->getItem('key_2');
$item->set('abcde');
$item->expiresAfter(60);
$redis->save($item);
return new Response('saved');
}
}
?>
Результат выполнения кода:
saved
Пример
Давайте удалим элемент из кэша по ключу:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentCacheAdapterRedisAdapter;
use SymfonyComponentRoutingAttributeRoute;
class CacheController extends AbstractController
{
#[Route('/cache/delete', name: 'cache_delete')]
public function delete(): Response
{
$redis = new RedisAdapter(
new \Redis(),
'app'
);
$redis->deleteItem('key_1');
return new Response('deleted');
}
}
?>
Результат выполнения кода:
deleted
Смотрите также
-
класс
Cache,
который предоставляет методы кэширования -
метод
getItem,
который получает элемент кэша по ключу -
класс
FilesystemAdapter,
который хранит кэш в файловой системе -
класс
ArrayAdapter,
который хранит кэш в массиве