Set Up Redis as Application Cache with TTL
Configure Redis as a fast in-memory cache for your application with key expiration policies to manage memory efficiently.
Prerequisites
- -Redis installed and running
- -redis-cli available
Steps
Verify Redis is running
Confirm that your Redis server is up and responding to commands.
You should see PONG as the response. If not, start Redis with 'redis-server' or 'sudo systemctl start redis'.
Set a key with a TTL
Store a cached value with an automatic expiration time in seconds.
EX sets expiration in seconds. Use PX for milliseconds.
Check remaining TTL on a key
Inspect how many seconds remain before a key expires.
Set a default eviction policy
Configure Redis to automatically evict least-recently-used keys when memory is full.
This changes the running config only. Add 'maxmemory-policy allkeys-lru' to redis.conf for persistence across restarts.
Set a memory limit
Cap Redis memory usage to prevent it from consuming all available RAM.
Verify cache hit and miss with GET
Retrieve a cached value and confirm it returns data before expiration and nil after.
Full Script
FAQ
Discussion
Loading comments...