I setup Redis cache for my web app. I want a blank database and get rid of all keys. How can I delete everything in Redis cache? How do I flush my Redis cache using the Linux/Unix command line option?
You can flush cache/database and delete all keys using any one of the following command:
- FLUSHDB command – Delete all the keys of the currently selected DB.
- FLUSHALL command – Delete all the keys of all the existing databases, not just the currently selected one.
Please note that Redis version 4.0.0 and above is now able to delete keys in the background in a different thread without blocking the server. An ASYNC option was added to FLUSHALL and FLUSHDB in order to let the entire dataset or a single database to be freed asynchronously.
Warning: Once removed data/keys/values can not be recovered. Be careful when typing the following commands.
Syntax to flush Redis cache
The syntax is:
redis-cli -n DB_NUMBER FLUSHDB
redis-cli -n DB_NUMBER FLUSHDB ASYNC
redis-cli FLUSHALL ASYNC
Type the following command to delete all the keys of the DB # 4:
$ redis-cli -n 4 FLUSHDB
To remove all the keys of all the existing database, run:
$ redis-cli FLUSHALL
Automation of deleting Redis cache using Ansible devops tool
Say you have 10 different Redis server running and you want to remove all the keys of all existing DBs. Create a host file as follows:
$ cat hosts
[redis] ansible_user=vivek vm1-eu vm2-us vm3-bom vm4-del vm5-nyc vm6-eu-2 vm7-linod-fr-1 vm8-do-blr-1 vm9-do-blr-2 vm10-linod-tx-1
Now all you have to do is run the following command (assuming that SSH keys are set between your workstation and all other VMs/bare metal servers)
$ ansible -i hosts redis -m command -a '/usr/bin/redis-cli FLUSHALL'
vm1-eu | SUCCESS | rc=0 >> OK vm2-us | SUCCESS | rc=0 >> OK vm3-bom | SUCCESS | rc=0 >> OK vm4-del | SUCCESS | rc=0 >> OK vm5-nyc | SUCCESS | rc=0 >> OK vm6-eu-2 | SUCCESS | rc=0 >> OK vm7-linod-fr-1 | SUCCESS | rc=0 >> OK vm8-do-blr-1 | SUCCESS | rc=0 >> OK vm9-do-blr-2 | SUCCESS | rc=0 >> OK m10-linod-tx-1 | SUCCESS | rc=0 >> OK