In the Scaling Symfony sessions with Memcached article we focused on scaling our Symfony session with Memcached.
Memcached is very easy to set-up and use but it lacks of persistence and some other cool stuffs we can find in Redis.
What’s Redis?
Redis in an in-memory data structure store. It is very reliable and widely used. You can find every info on the official page: redis.io
Why Redis?
Because if offers persistence and it could be a functionality you need for your sessions!
How can my Symfony sessions use Redis?
There’s a bundle for that! https://github.com/snc/SncRedisBundle
It abstracts the PHP connection to Redis for you. Two options are available to let your PHP talk to Redis: Predis and phpredis.
After having installed the bundle you need to configure it.
First you need to tell Symfony that you want to use the Redis session handler.
In you config.yml simply put:
1 2 3 |
framework: session: handler_id: snc_redis.session.handler |
Now it’s time to configure the bundle itself:
1 2 3 4 5 6 7 8 9 10 11 |
snc_redis: clients: session_client: dsn: '%redis_dsn_session%' logging: false # https://github.com/snc/SncRedisBundle/issues/161 type: phpredis session: client: session_client locking: false prefix: session_prefix_ ttl: '%session_ttl%' |
As you can see the bundle lets you declare some clients and we declared a client called “session_client” using phpredis. We need to tell it where Redis server is: dsn is for that. It’s advisable to configure it inside your parameters.yml file in order to have different Redis servers for different setups. As you can see we also disabled logging because, as the time of writing, there’s a bug using it together with Monolog.
In the snc_redis.session key you have to tell the bundle how you want your sessions to work. As for the dns it’s better to configure the session time to live in your parameters.yml otherwise you’ll have the same value both in production and dev environment: that’s not very smart because you don’t want to be log out very often during development.
With few lines of configuration we have now our sessions on Redis: hope you find it useful!