How to clear Redis Cache

Published on 2022-02-11

Redis is a data structure with in-memory capabilities. This article takes you through what Redis is and how to clear its cache.

What is Redis?

Redis (Remote Dictionary Server) is a memory-based key-value database, cache, and message broker. Redis supports strings, lists, maps, sets, sorted sets, HyperLogLogs, bitmaps, streams, and spatial indices. The project was planned and managed by Salvatore Sanfilippo.

Redis popularized the concept of a system that can act both as a store and a cache by employing a design in which the data is constantly being modified and essentially read for all intents. It focuses mainly on the computer memory but, it is also stored on the disc in a format that most of the part is unsuitable for some random data access with the data being reconstructed in memory only once the system restarts.

Redis has no connection to a relational database management system (RDBMS), which is basically significant in terms of the data model. Instead of a query from the user, the database engine gets specific actions on abstract data types in an extensive way. For getting results, all the information must be stored typically in such a way that later, it can be retrieved swiftly without the use of any secondary index, aggregations, or other RDBMS features in the future in a very precise way.

To mimic the data-holding process, the Redis implementation heavily relies on the fork system call, which allows its parent process to continue serving clients. At the same time, the intermediate node transfers the data to the disc.

Redis cache

Redis is a great way to create a highly accessible in-memory cache that will help your relational or NoSQL database and application by reducing data access latency, increasing performance, and relieving strain. Redis can respond to frequently requested items in milliseconds or less, and it allows you to grow for larger loads without needing to upgrade to a more expensive backend. Furthermore, Redis caching is commonly used for database query results, persistent session caching, web page caching and caching of frequently used assets like photos, files, and metadata.

Clearing Redis Cache

Let’s assume that the Redis Cache is already being installed on your device and configured with the server. We will explore how to clear the Redis Cache in this section.

Clearing Redis cache with “redis-cli” command

The simplest and quickest way to clear the Redis cache is to use the CLI command. In Redis, the databases are kept separate. Using CLI commands, you may wipe the keys from all databases at once or from a single database. To erase the Redis database cache, use the following syntax:

redis-cli [number of the database] [option]

Where:

[option]: Either clear all databases or a single database.

[database number]: Enter the database number you want to delete.

Once the database key has been deleted, it cannot be retrieved.

Clearing single database

If you wish to clean a single database, use the following command:

redis-cli flushdb

The command flushdb without any arguments will clean the database you’ve chosen. You may use -n arguments to specify a database by number.

redis-cli -n [database number] flushdb

Using the Async function will clear the keys in the background without causing the service to be blocked. This function can be used with the -n option.

redis-cli -n [database number] flushdb async

Clearing every database

Using the following command will remove all the keys from Redis databases:

redis-cli flushall

You may clear the keys in the background in Redis 4.0.0 without stopping your server. It would help if you used the async argument in the syntax to make the process async.

redis-cli flushall async

This is how all the keys from databases will get deleted.

Working with java client

Let’s look at how to delete keys with the Jedis Java client.

Starting an embedded Redis

We’ll use an available port to establish an embedded Redis server to test with:

RedisService redisServer = new RedisServer(port);

The hostname for our Jedis client is localhost, and the port is the same:

Jedis jedis = new Jedis("localhost", port);

Clearing single database

Let’s enter some information into the database and see whether it is remembered:

String key = "key";
String value = "value";
jedis.set(key, value);
String received = jedis.get(key);
assertEquals(value, received);

Let’s now use the flushDB method to flush the database:

jedis.flushDB();
assertNull(jedis.get(key));

As can be seen, they are attempting to access the value after flushing produces null.

Clearing all databases

Only the current database will be flushed with the flushDB method. We use the flushAll function to clean all of the databases:

jedis.flushAll();

We could see if it worked by doing the following:

jedis.select(0);
assertNull(jedis.get("key1"));
assertNull(jedis.get("key2"));
jedis.select(1);
assertNull(jedis.get("key1"));
assertNull(jedis.get("key2"));

Automatically Clear Redis Cache with Ansible

You won’t be able to clean the Redis cache using the previously mentioned methods while having a large number of servers. It will require a long time to execute. You will need to automate the process to make it faster. For example, Ansible may wipe the Redis cache from all of your configured servers at once. Use this command to get started:

ansible all -m command -a '/usr/bin/redis-cli flushall

The ‘flushall’ command is sent to all servers in the Ansible inventory file using this syntax.

Type all in the Ansible inventory file to pick all remote hosts.

-m: m specifies a module that must be executed.

-a: a assembles the argument required by the module.

Why do we need to clear Redis caches keys?

To better understand the significance of the cache’s key clearance, we will take one of the business domains examples. Suppose catalog product entities are basically not developed directly in different business solutions or projects; instead, they, for the most part, are handled in an external product management system and imported into imposed business project via a bespoke import procedure, kind of contrary to popular belief. This operation is mostly carried out every 10 minutes by a relevant engine minion. Because of the type of editorial activity for a product in the external product management system, it may specifically take pretty much more than 10 minutes.

The product import procedure modifies all current versions of the product sellable item entity rather than creating a new entity version every time a product is generally modified in a subtle way. The cached object in the Redis cache store is not automatically removed or generally refreshed when an existing entity version is mostly modified in a big way. The cache policy for the sellable items cache is set to, for the most part, expire in 2 hours by default. This implies that seeing product changes in the project might really take up to 2 hours, showing how the sellable items cache’s cache is mostly set to, that is 2 hours, as mentioned, which specifically is pretty significant.

The disparity between what generally is saved in the project database and what a content creator sees in Business Tools (the cached version of the entity) for all intents and purposes can be confusing and lead to data integrity concerns. So, the cache policy for the sellable items cache is set for all intents and purposes expire in 2 hours by default, which is quite significant. As a result, it’s critical to specifically be able to delete the cached objects associated with an updated product from the Redis cache store as soon as the product kind is updated.

Conclusion

In this article, we specifically got the knowledge of how to run Redis and the Redis-CLI command in the Docker. Furthermore, we learned to integrate the Jedis client for Java with an embedded Redis server subtly. We generally observed how to keep data in different Redis databases and to use the flush commands to particularly clear one or multiples of them.