C# Programming
Published in

C# Programming

Azure Redis Cache or Local Containerized Redis Cache Instance with .Net Core Web API Application

Hi All, today we are going to learn how to use Redis Cache with .Net Core Web API application. This is a continuation of https://arkapravasinha.medium.com/redis-cache-with-net-core-console-application-933a56acc9f8

We are going to create our Redis Instance locally using docker.

After that , we will see how to use Azure Redis Cache with our application.

Things Required:

  1. Docker Desktop and Docker CLI

Nuget Package Used:

<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="5.0.1" /><PackageReference Include="StackExchange.Redis" Version="2.2.4" />

Steps:

  1. First we will create a redis instance in our local systems, to do that open Command Prompt.

3. Now create a Redis Container and assign ports , Redis run from 6379 port so assign the inner container port to 6379 so that we will be able to communicate with Redis Instance.

docker run --name <instance-name> -p  5001:6379 -d redis

4. After this command executed successfully, you can check the status of container by running “docker ps -a”.

docker ps -a

5. To Check if Redis is up or not follow below steps,

a. Run “docker exec -it <instance-name> sh”, to run shell in the container

b. Then type “redis-cli” and press enter

c. Now you are in redis cli, run “Ping”, if it returns pong, means server is up and listening.

6. So now our Redis server has been deployed, now Open VS2019

7. Create a Asp.Net Core Web Api project. By default it will create a API with weather forcasting capabilities, so we are going to leverage that.

8. Install above mentioned Nuget packages.

9. Now first we need to Configure our web api, to connect to Redis Instance. to do that, we will modify the Startup.cs and configure services with AddStackExchangeRedis() method and configure the options as below,

10. Now we will create , our services, IWeatherForecastService interface and it’s concrete implementation WeatherForecastService class and will setup the dependency injection in Startup.cs(for dependency injection of the services please refer to above snippet). In WeatherForecastService class’s constructor we will inject IDistributedCache to access the Redis Instance and also we will inject ILogger<T> to log informations. Please find the below code snippet for your reference.

10. Now in our controller(WeatherForecastController.cs) , we will use our services to get the data. Please find the below code snippet for your reference,

11. Oh I forgot to mention one thing, I have create some extension methods to put the data in cache and access the data from the cache, without these our code will not work. Please look at below code snippet,

12. Now our Application is ready to run. Clean and Build the solution and then run it. First Time it will fetch the data from in memory datastore and will put the data in cache so any subsequent request with in cache lifetime will be served from cache, if cache expired then again data will be fetched from in memory datastore, and push the data to cache, so that it will be again available.

Data screenshot:

run it in browser you can do it in Postman as well

Logs:

from the logs you can understand how we are fetching from cache

Redis Instance:

to open it, go to your docker desktop and select your redis instance and select cli and run the commands

If you are facing any issues , please refer to the below mentioned code repository.

Azure Steps:

  1. Now go to Azure Portal.

3. Click on Create. Select your Subscription, Select a Resource Group. if you want , you can create a new one. Provide a DNS name, it should be unique across azure cache domain, and select a region, I am choosing Central India as it is nearest to me so that latency will be less and select a consumption plan, I am choosing Basic for today’s demo purpose.

4. Now click on Review + Create and then click on Create, it will take some time to spun off new redis instance.

5. Once your Redis Instance is ready, Please go to your Redis Instance Resource. Now Click on Overview and then select Show Access Keys. It will open a Pop Up, there you will find your connection string. Now copy the Primary one and paste it somewhere safe for the time being.

6. Now open our project’s appsettings.json and change the connection string to recently copied one.

7. Now Clean and Rebuild the Solution and Run it. Voila we are done.

8. Now got Azure Portal again, and go to your redis instance. You will find an option called Console in the Overview. Click on that and run similar commands which we earlier ran on redis-cli in docker instance. You can also check the metrics.

Redis Console
Metrics

9. After you are done, Please delete the resource so that it will not incur any costs.

Please let me know your feedback guys.

Code Repository: https://github.com/arkapravasinha/Redis.Core.WebApi

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arkaprava Sinha

Software Engineer-III @Walmart , Cloud, IoT and DevOps Enthusiast