Using Redis Cache In Web API

Caching is the process of storing the data in a temporary storage for a specific period of time, so that from the next time onwards, when the data is requested, it can be provided from this temporary storage instead of the database.

What is Redis Cache?

As stated in Redis official site,

“Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.”

Please check more details on the Redis official site here.

Now, we will check, how to implement Redis Cache in Web API. 


I’m creating Web API with MVC 4, using Visual Studio 2010.

To start with, we will first install Redis Client in our system.

Just click this link and download the exe file.

Now, install Redis Client by double clicking the exe file.

After installation of Redis Client, take command prompt. (Search cmd in search and click the first result, as shown in the image, given below)-

In command prompt, type SET PATH=%PATH%;”c:\Program Files\redis” and press enter.

Now, type redis-server.exe and press enter.

Now, our Redis Server is ready.

Now, we will start creating our Web API and implement Redis Caching in it.

Step 1 - Open Visual Studio 2010 and click New Project. Select “Web” from the left menu and select “ASP.NET MVC 4 Web Application”.

Give name of the project as RedisCaching and click OK.

Step 2 - Select “Web API” from Project Template and view Engine as “Razor” and click OK.

Step 3 - Now, our API is created. Now, go to top menu and click “Tools”.

In the drop down, select “Library Package Manager > Package Manager Console”.

Step 4 - Now, we will get Package Manager Console at the bottom.

Just type “Install-Package CacheManager.StackExchange.Redis” there and click enter.

You may sometimes get an error, as shown below-

Step 5 - To resolve the error, shown above-

Go to Top menu > Tools > Extension Manager.

Click Update in the left menu.

Now, just update the NuGet Package Manager.

Step 6 - Now, open Package Manager Console, as done in step 3 and run the command, specified in step 4.

Now, our Redis Cache is successfully installed.

Step 7 - Now, we will create a class in Model Folder as “RedisConnection”.

Add the code, given below, to the class-

  1. public class RedisConnection  
  2. {  
  3.     static RedisConnection()  
  4.     {  
  5.         RedisConnection.lazyConnection = new Lazy<ConnectionMultiplexer>(() =>  
  6.         {  
  7.             return ConnectionMultiplexer.Connect("localhost");  
  8.         });  
  9.     }  
  11.     private static Lazy<ConnectionMultiplexer> lazyConnection;  
  13.     public ConnectionMultiplexer Connection  
  14.     {  
  15.         get  
  16.         {  
  17.             return lazyConnection.Value;  
  18.         }  
  19.     }  
  20. }   

Step 8 - Now, we will add a controller.

Right click Controller folder > Click Add > Click Controller.

Now, give the name as RedisController and click Add.

Step 9 - Now, add the code, given below, to our controller-

  1. public class RedisController : Controller  
  2. {  
  3.     RedisConnection obj = new RedisConnection();  
  4.     public string GetDatetime()  
  5.     {  
  6.         string datetime = "";  
  7.         //Creating Redis database instance  
  8.         IDatabase db = obj.Connection.GetDatabase();  
  10.         //Getting value of "datetime" key  
  11.         datetime = db.StringGet("datetime");  
  13.         //If key not found in Redis database  
  14.         if (datetime == null)  
  15.         {  
  16.             datetime = Convert.ToString(DateTime.Now);  
  18.             //Setting value for key with Expiry time of 5 Minutes  
  19.             db.StringSet("datetime", datetime, TimeSpan.FromMinutes(5));  
  20.         }  
  21.         return datetime;  
  22.     }  
  23. }   

Here, we are creating a method to return the current date & time.

Considering the code, shown above, you can see, we are creating an instance of Redis database. Next, we checked whether the database has a key ”datetime”. If yes, our string datetime will get the corresponding value from Redis database.

If the situation is different, we will add the key “datetime” to database with the current datetime. We have given an expiry time for key as 5 minutes. For the next five minutes, we will get date, which is stored in Redis Cache.

Just Run API. URL format will be http://localhost:{Some number}/Redis/Getdatetime.

While running API URL, shown above, you can see the same date for 5 minutes, after which it gets updated.


In this API, we learned how to implement Redis Cache with Web API. In the files attached, I have provided the codes to save the datatable as a JSON string in Redis database and retrieve it. The output is in a JSON data.

Hope, this will be helpful for someone out there!

Similar Articles