Redis is an open-source in-memory data structure store, which is used as a database, and caching. It supports various data structures, such as strings, hashes, lists, sets, etc.
The primary use of Redis is to store key-values, so it can be used for caching. Redis is highly available and optimized for speed, that’s why Redis is a popular distributed caching engine right now.
In this tutorial, we will see how to clear Redis cache.
- The latest version of Redis
- Access to the Command Line or Terminal Window
Clear Redis Cache With the redis-cli Command
The easiest and the quickest way to clear Redis cache is t use the CLI command.
Redis store the databases individually separately. CLI commands will allow you to clear the keys from all databases at once, or any single specified database.
Redis-cli Command Syntax:
Syntax to delete Redis database cache:
redis-cli [database number] [option]
- [option]: Clear all databases or anyone specific database.
- [database number]: Put the number of the database you want to clear.
Note: Once deleted, you cannot recover the databases key.
How to Delete All Keys?
Delete all the keys from Redis databases by using the following command:
In updated Redis 4.0.0, you can clear keys in the background, without blocking your server. You have to async the process using the async parameter in the syntax.
redis-cli flushall async
This is how you delta all the keys from databases.
Deleting Keys from a Specific Database
If you want to clear any single specific database, you can do with this command:
Using ‘flushdb’ command without any parameters will clear the database you have selected.
To specify a database with a number, you can use -n parameters.
redis-cli -n [database number] flushdb
Using Async function will clear the keys in the background, without blocking the server. You can use this function with -n parameter.
redis-cli -n [database number] flushdb async
Automatically Clear Redis Cache with Ansible
If the number of servers is large, then you can’t use the method mentioned above to clear Redis cache. It will take lots of time.
You have to automate the process to speed up the works. Tools like Ansible can clear Redis cache of all of your servers at the same time.
Use this command:
ansible all -m command -a '/usr/bin/redis-cli flushall'
This syntax commands’ flushall’ to all the server available in the Ansible inventory file.
- all: to select all the remote hosts in Ansible inventory file
- -m: m is used to assign a module that needs to be executed
- -a: a arrange the argument required by the module.
In this tutorial, you learned clearing Redis Cache with CLI. Now you know how to use flush commands, and automate clearing Redis cache with Ansible.
For more information, you can read Redis docs.
If you encounter any problem, leave it in the comment section.