Setting expiration on keys
In the recipe Managing keys in Chapter 2,Data Types, we learned that Redis keys can be deleted by using the DEL
or UNLINK
command. Besides deleting keys manually, we can also ask Redis to delete keys automatically by setting the timeout on keys. In this recipe, we will illustrate how to set the timeout on Redis keys and explain the key expiration mechanism in Redis.
Getting ready…
You need to finish the installation of the Redis Server as we described in the Downloading and Installing Redis recipe in Chapter 1, Getting Started with Redis.
How to do it...
To show how to set expiration on keys, we store the IDs of five restaurants that are closest to the user's current location in a Redis list. As the user's location may change frequently, we should set a timeout on this Redis list. After the timeout has expired, we will fetch the restaurant list again using the current location:
- Create a Redis list of restaurant IDs at key
closest_restaurant_ids
:
127.0.0.1:6379> LPUSH...