Redis is an open-source solution for data structure storage. It is primarily used as a key-value store, which allows it to work as a database, cache storage, and message broker.
In this tutorial we will cover different ways you can delete these key-values (keys) and clear Redis cache.
Clear Redis Cache With the redis-cli Command
The easiest way to clear Redis cache is to use the
Databases in Redis are stored individually. Using the
redis-cli command allows you to either clear the keys from all databases, or from a single specified database only.
redis-cli Command Syntax
redis-cli command uses the following syntax:
redis-cli [database number] [option]
[option]– Lets you choose between clearing all databases or one specific database of your choice.
[database number]– Lets you specify which database you want to clear.
Note: Once you delete keys from a database, they can no longer be recovered.
Deleting All Keys
To delete keys from all Redis databases, use the following command:
As of version 4.0.0, Redis can clear keys in the background without blocking your server. To do this, use the
flushall command with the
redis-cli flushall async
Deleting Keys from a Specific Database
Use the following command to clear a specific database only:
flushdb command without any parameters clears the currently selected database. Use the
-n parameter with the database number to select a specific database you want to clear:
redis-cli -n [database number] flushdb
You can also use the
async option when clearing keys from individual databases:
redis-cli -n [database number] flushdb async
Automating Cache Clearing Using Ansible
If you have a large number of Redis servers running, clearing the cache for each one manually takes time.
To speed this process up, use a tool like Ansible to clear the cache on all your Redis servers at the same time:
ansible all -m command -a '/usr/bin/redis-cli flushall '
Running this command applies the
flushall command to every server in your Ansible inventory file:
all– Lets you choose all the remote hosts in the Ansible inventory file.
-m– Lets you choose a module to execute.
-a– Provides an argument for the module. In this case, the command module runs the
After going through this tutorial, you have learned how to use the
flush commands to clear your Redis cache.
Next, learn more about Redis by exploring Redis Data Types.