Step 31: Using Redis to Store Sessions
Using Redis to Store Sessions
Depending on the website traffic and/or its infrastructure, you might want to use Redis to manage user sessions instead of PostgreSQL.
When we talked about branching the project’s code to move session from the filesystem to the database, we listed all the needed step to add a new service.
Here is how you can add Redis to your project in one patch:
patch_file
--- a/.symfony.cloud.yaml
+++ b/.symfony.cloud.yaml
@@ -4,6 +4,7 @@ type: php:7.4
runtime:
extensions:
+ - redis
- blackfire
- xsl
- pdo_pgsql
@@ -26,6 +27,7 @@ disk: 512
relationships:
database: "db:postgresql"
+ redis: "rediscache:redis"
web:
locations:
--- a/.symfony/services.yaml
+++ b/.symfony/services.yaml
@@ -15,3 +15,6 @@ varnish:
files:
type: network-storage:1.0
disk: 256
+
+rediscache:
+ type: redis:5.0
--- a/config/packages/framework.yaml
+++ b/config/packages/framework.yaml
@@ -7,7 +7,7 @@ framework:
# Enables session support. Note that the session will ONLY be started if you read or write from it.
# Remove or comment this section to explicitly disable session support.
session:
- handler_id: '%env(DATABASE_URL)%'
+ handler_id: '%env(REDIS_URL)%'
cookie_secure: auto
cookie_samesite: lax
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -17,3 +17,7 @@ services:
image: blackfire/blackfire
env_file: .env.local
ports: [8707]
+
+ redis:
+ image: redis:5-alpine
+ ports: [6379]
Isn’t it beautiful?
“Reboot” Docker to start the Redis service:
$ docker-compose stop
$ docker-compose up -d
Test locally by browsing the website; everything should still work as before.
Commit and deploy as usual:
$ symfony deploy
Going Further
This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.