How to Set Expiry to Multiple Keys in Redis
Often, developers forget to set an expiry on keys, and redis begins to run out of memory. While you can set an expiry to newly generated keys, you still need a way to set an expiry to keys already sitting in memory.
This command will set expiry to keys matching users:*
How does the Script Work?
- First, we use
redis-cli --scan --pattern <pattern>to get a list of keys, one key per line.
- We then run an awk script for each key. This awk script is a little complex, so we will break it down
- The awk script has a command template
expire __key__ 1000. This is the command that will run for all keys.
- For each matching key, the awk command replaces
__key__with the actual key
- Next, we convert the string command to redis protocol format. This is the raw format that redis understands.
- Finally, we pipe the raw commands to redis-cli using the –pipe flag. This is the most efficient way to send bulk commands to redis.
Customizing this Script
- You can customize
cmd_templateto run any single key redis command against multiple keys matching a pattern.
- Redis scan allows glob style patterns only, regex is not supported. So
users:123as well as
users:123:favourites. You can put in a
grepin the pipeline after the first redis-cli and before the awk script.
- If your redis server is not on localhost, you will have to provide the host, port and password twice in the command, basically whenever you call redis-cli.