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).
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 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.