Delete Single or multiple or All keys in Redis .NET – Guidelines

Delete keys in Redis Cache cluster NET

Today in this article we shall see how to Delete keys in Redis Cache cluster .NET C# applicaiton. We shall see various useful commands and understand their behavior to achieve the same.

Today in this article, we will cover below aspects,

We will see a few approaches which are supported in .NET-based applications.

Its recommended using Use the SCAN Vs KEYS command as we learned in the Best practices of Redis Cache guidelines


Delete single key in Redis from the current database

Delete single key in Redis from the current database can be achieved using supported sync and async methods as shown in the below example,

Example

The below example uses the dependency injection approach for IConnectionMultiplexer and uses the object to perform read, write, delete operations on the cache.

     public async Task<bool> DeleteID(int employeeID)
        {
            await _redisDBAsync.KeyDeleteAsync(employeeID);
            return true;
        }

_redisDBAsync is an instance of IDatabaseAsync which is created using IConnectionMultiplexer related GetDatabase method.

To get more details about the same, please visit below article of best practices of Redis using IConnectionMultiplexer

Below is a sample snippet from the above article where we do DI for IConnectionMultiplexer,

redis delete keys c

Delete multiple keys in Redis

Please use the same above logic in the loop and delete multiple keys.

Delete all keys in Redis the database

Delete all keys in Redis the database can be achieved using FlushDatabaseAsync or FlushAllDatabasesAsync methods.

Example

public async Task DeleteAllkeys()
         {
             string host = _configuration.GetValue("RedisCache:Host");
             string port = _configuration.GetValue("RedisCache:Port");
             var iServer = _redisCache.GetServer(host, port);
             await iServer.FlushDatabaseAsync();         
             return true;     
        }

Above we are deleting all the keys of the selected database. 

Delete all keys in Redis from all the database

 await iServer.FlushAllDatabasesAsync ();

Note – Please be extra cautious on using these commands as they will delete all the cache data from the server.

FlushDatabaseAsync command – Delete all the keys of the currently selected DB. 

FlushAllDatabasesAsync – Detele all keys of all the database on the server

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *