Use Redis in Symfony

Install redis server:

sudo apt-get install redis-server

Copy backup configuration file:

sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.default

Check if redis is installed correctly by:

redis-cli

Install Predis library:

composer require predis/predis

Add to .env file

REDIS_HOST=127.0.0.1
REDIS_PORT=6379

In services.yaml add following:

services:
    Predis\Client:
        class: Predis\Client
        arguments:
            - { host: '%env(REDIS_HOST)%' }

Example of predis client usage in Controller:

    const PREFIX = 'REDIS_TEST';

private $redis;

public function __construct(Client $redis)
{
$this->redis = $redis;
}

/**
* @Route("/default", name="default")
*/
public function index()
{
$key = \sprintf('%s:%d', self::PREFIX, (new \DateTime())->format('Ymd'));
$data = [];

if (!$this->redis->exists($key)) {
$this->redis->pipeline(
function ($pipe) use ($key, $data) {
/* @var Client $pipe */
$pipe->rpush(\sprintf('%s:key_list', self::PREFIX), [$key]);
$pipe->hmset(
$key,
['json' => json_encode(['first' => '123','second' => '456'])]
);
}
);
}

dump($this->redis->lrange(\sprintf('%s:key_list', self::PREFIX), 0, -1));
dump(json_decode($this->redis->hgetall($key)['json']));

return $this->render('default/index.html.twig', [
'controller_name' => 'DefaultController',
]);
}

	

Leave a Reply

Your email address will not be published. Required fields are marked *