Skip to main content

Using Redis distributed cache in dotnet core with helper extension methods

Redis cache is out process cache provider for a distributed environment. It is popular in Azure Cloud solution, but it also has a standalone application to operate upon in case of small enterprises application.

How to install Redis Cache on a local machine?
Redis can be used as a local cache server too on our local machines.

At first install, Chocolatey https://chocolatey.org/, to make installation of Redis easy. Also, the version under Chocolatey supports more commands and compatible with Official Cache package from Microsoft.
After Chocolatey installation hit choco install redis-64.
Once the installation is done, we can start the server by running redis-server.

Distributed Cache package and registration
dotnet core provides IDistributedCache interface which can be overrided with our own implementation. That is one of the beauties of dotnet core, having DI implementation at heart of framework.

There is already nuget package available to override IDistributedCache i:e Microsoft.Extensions.Caching.Redis.

To use we need to register service by using an extension method from the package.

 services.AddDistributedRedisCache(options =>  
 {  
   options.Configuration = Configuration["<Redis connection string>"];  
   options.InstanceName = "<prefix name for easy identification (optional)>:";  
 });  

How to use Redis Cache based on IDistributedCache?
Since Redis cache registration is done, we can use IDistributedCache reference in the constructor to utilize Redis.
Default distributed cache option.
Default options from IDistributedCache
The image on the right side provide all options from IDistrubutedCache. Also, you can see I have used it on constructor to get an instance from DI. This is a Disposable implementation so if you are you are not using DI then disposing of the object needs to be taken care explicitly.

As you can see from function names, these are pretty basic to use. The idea is to extend the APIs with C# extension methods through which we can take care of serialization and deserialization of any object too.

In the extension method, I am going to use GetOrSetCacheAsync which would take care of getting or setting of value automatically in the cache, if the cache is available in Redis than it would get from it else it would save in Redis and get the value, we would see how to use shortly.

The GetOrSetCacheAsync function backed by GetCacheValueAsync to get from Redis and to save StoreValueAsync. These all are generic version. Here is the whole implementation of Extension methods.

 /// <summary>  
 /// Extension methods for caching.  
 /// </summary>  
 public static class CacheExtension  
 {  
   /// <summary>  
   /// Gets or set cache asynchronous.  
   /// </summary>  
   /// <typeparam name="TResult">The type of the result.</typeparam>  
   /// <param name="cache">The distributed cache interface.</param>  
   /// <param name="key">The key for storing cache.</param>  
   /// <param name="storingItem">The storing item.</param>  
   /// <param name="cacheRule">The cache rule.</param>  
   /// <returns>  
   /// The result for stored item.  
   /// </returns>  
   public static async Task<TResult> GetOrSetCacheAsync<TResult>(this IDistributedCache cache, string key,  
     Func<TResult> storingItem, DistributedCacheEntryOptions cacheRule = null)  
     where TResult : class  
   {  
     var cachedValue = await cache.GetCacheValueAsync<TResult>(key);  
     if (cachedValue == null)  
     {  
       return await cache.StoreValueAsync(key, storingItem, cacheRule);  
     }  
     return cachedValue;  
   }  
   /// <summary>  
   /// Gets the cache value asynchronous.  
   /// </summary>  
   /// <typeparam name="TResult">The type of the result.</typeparam>  
   /// <param name="cache">The cache.</param>  
   /// <param name="key">The key for caching.</param>  
   /// <param name="storingItem">The storing item.</param>  
   /// <returns>Value of cached item.</returns>  
   public static async Task<TResult> GetCacheValueAsync<TResult>(this IDistributedCache cache, string key)  
       where TResult : class  
   {  
     if (IsNullOrEmpty(key))  
     {  
       throw new ArgumentNullException(nameof(key));  
     }  
     var cachedValue = await cache.GetStringAsync(key.ToLower(CultureInfo.InvariantCulture));  
     if (IsNullOrEmpty(cachedValue))  
     {  
       return null;  
     }  
     return JsonConvert.DeserializeObject<TResult>(cachedValue);  
   }  
   /// <summary>  
   /// Stores the value in cache.  
   /// </summary>  
   /// <typeparam name="TResult">The type of the result.</typeparam>  
   /// <param name="cache">The cache.</param>  
   /// <param name="key">The key for caching.</param>  
   /// <param name="storingItem">The storing item.</param>  
   /// <param name="cacheRule">The cache rule.</param>  
   /// <returns>  
   /// Value of caching item.  
   /// </returns>  
   /// <exception cref="ArgumentNullException">key</exception>  
   public static async Task<TResult> StoreValueAsync<TResult>(this IDistributedCache cache, string key,  
     Func<TResult> storingItem, DistributedCacheEntryOptions cacheRule = null)  
     where TResult : class  
   {  
     if (IsNullOrEmpty(key))  
     {  
       throw new ArgumentNullException(nameof(key));  
     }  
     var storingValue = storingItem();  
     if (storingValue != null && storingValue != default(TResult))  
     {  
       var redisKey = key.ToLower(CultureInfo.InvariantCulture);  
       var value = JsonConvert.SerializeObject(storingValue);  
       if (cacheRule != null)  
       {  
         await cache.SetStringAsync(redisKey, value, cacheRule);  
       }  
       else  
       {  
         await cache.SetStringAsync(redisKey, value);  
       }  
     }  
     return storingValue;  
   }  
 }  

You can add your own implementation based on a need basis.

How to use created extension methods?
The best way to show this is through Unit Test class, so here is the code which utilizes and explains whole custom extension methods.

 [TestClass]  
 public class RedisCacheTest  
 {  
   private readonly IDistributedCache CacheStore;  
   public RedisCacheTest()  
   {  
     CacheStore = new RedisCache(new RedisCacheOptions  
     {  
       Configuration = "localhost:6379",  
       InstanceName = "Test:"  
     });  
   }  
   // INFO: Gets or sets the value based on request.  
   //    If it is first call it would save the value in Redis   
   //    and for second call onwards it would just receive the value from cache.  
   // WARNING: If we use same method to update value in cache again, it would not save.   
   //     Check OverWriteCache() and StoresCacheOnce() function  
   [TestMethod]  
   public async Task CacheStoreIsSame()  
   {  
     await CacheStore.GetOrSetCacheAsync("key", () =>  
     {  
       // Do some sort of process and return object.  
       return new RedisStoreClass("value");  
     });  
     var val = await CacheStore.GetCacheValueAsync<RedisStoreClass>("key");  
     Assert.IsTrue(val.Name == "value");  
   }  
   // INFO: Expiration test after 1 millisecond delay.  
   [TestMethod]  
   public async Task CacheExpire()  
   {  
     var cacheKey = "cache:expiration:test";  
     await CacheStore.GetOrSetCacheAsync(cacheKey,  
       () => new RedisStoreClass("value"), new DistributedCacheEntryOptions  
       {  
         AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(100)  
       });  
     await Task.Delay(101);  
     var cachedValue = await CacheStore.GetCacheValueAsync<RedisStoreClass>(cacheKey);  
     Assert.IsNull(cachedValue);  
   }  
   // INFO: Overwriting cache.  
   [TestMethod]  
   public async Task OverWriteCache()  
   {  
     var cacheKey = "cache:overwrite";  
     await CacheStore.GetOrSetCacheAsync(cacheKey, () => new RedisStoreClass("value"));  
     await CacheStore.StoreValueAsync(cacheKey, () => new RedisStoreClass("value2"));  
     var cachedValue = await CacheStore.GetCacheValueAsync<RedisStoreClass>(cacheKey);  
     Assert.AreEqual(cachedValue.Name, "value2");  
   }  
   [TestMethod]  
   public async Task RemoveCache()  
   {  
     var cacheKey = "cache:remove";  
     await CacheStore.GetOrSetCacheAsync(cacheKey,  
       () => new RedisStoreClass("value"));  
     await Task.Delay(10000);  
     await CacheStore.RemoveAsync(cacheKey);  
     var cachedValue = await CacheStore.GetCacheValueAsync<RedisStoreClass>(cacheKey);  
     Assert.IsNull(cachedValue);  
   }  
   // INFO: Case insensitive check  
   [TestMethod]  
   public async Task CaseInsensitiveKey()  
   {  
     var cacheKey = "cache:InsensitiveKey";  
     await CacheStore.GetOrSetCacheAsync(cacheKey,  
       () => new RedisStoreClass("value"));  
     var val = await CacheStore.GetCacheValueAsync<RedisStoreClass>(cacheKey.ToUpperInvariant());  
     Assert.IsNotNull(val);  
   }  
   // INFO: If we use GetOrSetCacheAsync multiple times, new value won't be saved.  
   [TestMethod]  
   public async Task StoresCacheOnce()  
   {  
     var cacheKey = "cache:StoreOnce";  
     await CacheStore.GetOrSetCacheAsync(cacheKey,  
       () => new RedisStoreClass("value"));  
     await CacheStore.GetOrSetCacheAsync(cacheKey,  
       () => new RedisStoreClass("value2"));  
     var val = await CacheStore.GetCacheValueAsync<RedisStoreClass>(cacheKey);  
     Assert.AreEqual(val.Name, "value");  
   }  
 }  
 internal class RedisStoreClass  
 {  
   public string Name { get; set; }  
   public RedisStoreClass(string name)  
   {  
     Name = name;  
   }  
 }  

Please note that to make it simple, I have not used disposed on RedisCache instance.




Comments

  1. Dear Sir
    how can I delete all redis cache with some pattern key

    Example: I have 3 key like this
    Key 1: :User:1 (1: is dynamic)
    Key 2: :User:2 (2: is dynamic)
    Key 3: :Role:1
    -> how can I delete key 1 and 2

    ReplyDelete
    Replies
    1. So, sorry for really late..... reply. You might not need now but adding here if it can help someone else.
      You can create an extension method to remove, which can loop and look for your provided pattern to delete.

      Delete

Post a comment

Popular posts from this blog

Elegantly dealing with TimeZones in MVC Core / WebApi

In any new application handling TimeZone/DateTime is mostly least priority and generally, if someone is concerned then it would be handled by using DateTime.UtcNow on codes while creating current dates and converting incoming Date to UTC to save on servers. Basically, the process is followed by saving DateTime to UTC format in a database and keep converting data to native format based on user region or single region in the application's presentation layer. The above is tedious work and have to be followed religiously. If any developer misses out the manual conversion, then that area of code/view would not work. With newer frameworks, there are flexible ways to deal/intercept incoming or outgoing calls to simplify conversion of TimeZones. These are steps/process to achieve it. 1. Central code for storing user's state about TimeZone. Also, central code for conversion logic based on TimeZones. 2. Dependency injection for the above class to be able to use global

Handling JSON DateTime format on Asp.Net Core

This is a very simple trick to handle JSON date format on AspNet Core by global settings. This can be applicable for the older version as well. In a newer version by default, .Net depends upon Newtonsoft to process any JSON data. Newtonsoft depends upon Newtonsoft.Json.Converters.IsoDateTimeConverter class for processing date which in turns adds timezone for JSON data format. There is a global setting available for same that can be adjusted according to requirement. So, for example, we want to set default formatting to US format, we just need this code. services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.DateTimeZoneHandling = "MM/dd/yyyy HH:mm:ss"; });

Data seed for the application with EF, MongoDB or any other ORM.

Most of ORMs has moved to Code first approach where everything is derived/initialized from codes rather than DB side. In this situation, it is better to set data through codes only. We would be looking through simple technique where we would be Seeding data through Codes. I would be using UnitOfWork and Repository pattern for implementing Data Seeding technique. This can be applied to any data source MongoDB, EF, or any other ORM or DB. Things we would be doing. - Creating a base class for easy usage. - Interface for Seed function for any future enhancements. - Individual seed classes. - Configuration to call all seeds. - AspNet core configuration to Seed data through Seed configuration. Creating a base class for easy usage public abstract class BaseSeed<TModel> where TModel : class { protected readonly IMyProjectUnitOfWork MyProjectUnitOfWork; public BaseSeed(IMyProjectUnitOfWork MyProjectUnitOfWork) { MyProject

Trim text in MVC Core through Model Binder

Trimming text can be done on client side codes, but I believe it is most suitable on MVC Model Binder since it would be at one place on infrastructure level which would be free from any manual intervention of developer. This would allow every post request to be processed and converted to a trimmed string. Let us start by creating Model binder using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Threading.Tasks; public class TrimmingModelBinder : IModelBinder { private readonly IModelBinder FallbackBinder; public TrimmingModelBinder(IModelBinder fallbackBinder) { FallbackBinder = fallbackBinder ?? throw new ArgumentNullException(nameof(fallbackBinder)); } public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bin

Making FluentValidation compatible with Swagger including Enum or fixed List support

FluentValidation is not directly compatible with Swagger API to validate models. But they do provide an interface through which we can compose Swagger validation manually. That means we look under FluentValidation validators and compose Swagger validator properties to make it compatible. More of all mapping by reading information from FluentValidation and setting it to Swagger Model Schema. These can be done on any custom validation from FluentValidation too just that proper schema property has to be available from Swagger. Custom validation from Enum/List values on FluentValidation using FluentValidation.Validators; using System.Collections.Generic; using System.Linq; using static System.String; /// <summary> /// Validator as per list of items. /// </summary> /// <seealso cref="PropertyValidator" /> public class FixedListValidator : PropertyValidator { /// <summary> /// Gets the valid items /// <

Channel, ChannelReader and ChannelWriter to manage data streams in multi-threading environment

I came across Channel class while working with SignalR which looks really interesting. By looking into NuGet packages ( https://www.nuget.org/packages/System.Threading.Channels ), it seems just 4 months old. The Channel class provides infrastructure to have multiple reads and write simuletensely through it's Reader and Writer properties. This is where it is handy in case of SignalR where data streaming needs to be done but is not just limited to that but wherever something needs to be read/write/combination of both in a multi-threading environment. In my case with SignalR, I had to stream stock data at a regular interval of time. public ChannelReader<StockData> StreamStock() { var channel = Channel.CreateUnbounded<StockData>(); _stockManager.OnStockData = stockData => { channel.Writer.TryWrite(stockData); }; return channel.Reader; } The SignalR keeps return type of ChannelReader<StockData> open so that whatev

Strongly typed SingalR on server and client end through TypeScript.

SignalR is a very flexible framework to create bidirectional communication between client and server. The general process that is followed won't allow to have strongly typed calls on the server and also in client code. We will look into how to make strongly typed calls on the server through interface and client end through TypeScript. SignalR - making strong type on server side code Since client-side methods are very dynamic in nature, so calling those from server side behaves similarly to allow any calls. SignalR Hubs are derived from Microsoft.AspNet.SignalR.Hub class, there is also a generic version available to follow typed items. Ex: The interface is the replication of possible calls that would be received on the client end and calling of client-side methods on server code. /// <summary> /// Client(JS) side chatting interface callbacks. /// </summary> public interface IChatHub { /// <summary> /// Gets the online users

Kendo MVC Grid DataSourceRequest with AutoMapper

Kendo Grid does not work directly with AutoMapper but could be managed by simple trick using mapping through ToDataSourceResult. The solution works fine until different filters are applied. The problems occurs because passed filters refer to view model properties where as database model properties are required after AutoMapper is implemented. So, the plan is to intercept DataSourceRequest  and modify names based on database model. To do that we are going to create implementation of  CustomModelBinderAttribute to catch calls and have our own implementation of DataSourceRequestAttribute from Kendo MVC. I will be using same source code from Kendo but will replace column names for different criteria for sort, filters, group etc. Let's first look into how that will be implemented. public ActionResult GetRoles([MyDataSourceRequest(GridId.RolesUserGrid)] DataSourceRequest request) { if (request == null) { throw new ArgumentNullExce

Centralized model validation both for MVC/WebApi and SPA client-side validation using FluentValidation

Validation is one of the crucial parts of any application. It has to validate on both client side and server side requests. What are target features or implementation from this article? Model validation for any given model. Centralized/One code for validation on both server-side and client-side. Automatic validation of model without writing any extra codes on/under actions for validation.  NO EXTRA/ANY codes on client-side to validate any form. Compatible with SPA. Can be compatible with any client-side validation framework/library. Like Angular Reactive form validation or any jquery validation libraries. Tools used in the implementation? FluentValidation : I feel DataAnnotation validation are excellent and simple to use, but in case of complex validation or writing any custom validations are always tricker and need to write a lot of codes to achieve whereas FluentValidations are simple even in case of complex validation. Generally, we need to validate incoming input ag