Redis Cache in .Net Core

Asiye Nur Kelle
Innovile
Published in
3 min readAug 26, 2020

Hello, in this text I will be writing about Redis and answering the questions like “Why should we use it”,“How to use Redis Cache in Asp.Net Core MVC projects”

What is Redis (Remote Dictionary Service)?

Redis is an open-source,NoSQL,key value formatted database that allows us to keep data in memory. We can save and use high level data structures with Redis.

Why should we use Redis?

Unlike the other databases, Redis keeps data in memory.Redis keeps data primarily in RAM of our machine.Other than that, it can record in disc at spesific periods if you would like to do so.That way we can prevent data loss and find our data in disc when we need it.one of the biggest advantage of redis is keeping data in memory,it can reduce reading and writing time to miliseconds.

How can we use Redis Cache in our .Net Core MVC projects?

To install Redis in our computer, we should download the latest stabil version from here and start the redis-server.exe.

Then, to include Microsoft.Extensions.Caching.StackExchangeRedis package from NuGet packages from our .Net Core project.

We make additions to startup.cs and appsettings.json for configuration settings. Because redis works in port 6379 by default in our pc, we set it as shown in the bottom.

Appsettings.json
Startup.cs

Now time to use methods provided by redis. These are mainly; add,search,delete,remove and clean the cache.😊

First of all, we define these methods in an interface.The reason we use the interface is that when we want to use Microsoft Cache structure, we can implement a single interface and fill in the same methods.By this means we can avaoid code confusion.

We then implement this interface and perform the necessary configuration definitions in the class Redis.

It’s time to fill our methods with Redis 😊

Redis wants us to serialize/deserialize the data when performing these operations.

Get method

Set method

Remove method

Clear method

Contains method

Finally, we can create a controller and use Redis by passing out RedisCacheService class to this controller by using DI.

Good Works 😊

--

--