In Ruby applications using Redis, you might need to automatically delete keys after a certain period. This is often used in caching scenarios, where stale data must be removed after its lifetime, or for session management where sessions expire after inactivity.
Example 1: Using EXPIRE
command to set a key to be deleted after a specific time (in seconds).
require 'redis' redis = Redis.new redis.set('key', 'value') redis.expire('key', 10) # Key will be deleted after 10 seconds
In this example, we connect to Redis, set a key-value pair with the set
method, and then use the expire
method to specify that the key should be deleted after 10 seconds.
Example 2: Setting expiration time while creating the key using SETEX
.
require 'redis' redis = Redis.new redis.setex('key', 10, 'value') # Key will be deleted after 10 seconds
With the setex
method, you can set a key-value pair and its expiry time simultaneously. The key 'key' will be automatically deleted after 10 seconds.
Q: Can I check the remaining time before a key is deleted?
A: Yes, you can use the TTL
command. For instance, redis.ttl('key')
would return the remaining time in seconds before 'key' is deleted.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.