Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Nov 25, 2022

Distributed Redis caching in ASP.NET Core

Автор:
Источник:
Просмотров:
3771

redis

In this article, we will see Distributed caching, Redis cache, and also Redis caching in ASP.NET Core.

Follow me on Github and Download source code from GitHub

Table of Content

  • What is distributed caching and its benefit
  • IDistributedCache interface
  • Framework provided to implement
  • Distributed Redis cache
  • Setting up Redis on Windows 10
  • Redis CLI commands
  • Steps to integrate Redis cache in ASP.NET core
  • Summary

What is distributed caching and its benefit

Distributed caching is when you want to handle caching outside of your application. This is also can be shared by one or more application/servers. Distributed cache is application-specific i.e., multiple cache providers that support distributed caches. To implement distributed cache, we can use Redis and NCache. We will see about Redis cache in detail.

A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm.

Benefits

  • Data is consistent throughout multiple servers.
  • This is more suitable for microservice architecture.
  • In case of loading balancing, this is recommended.
  • Multiple Applications / Servers can use one instance of Redis Server to cache data. This reduces the cost of maintenance in the longer run.

IDistributedCache interface

IDistributedCache Interface provides you with the following methods to perform actions on the actual cache

  1. GetAsync — Gets the Value from the Cache Server based on the passed key.
  2. SetAsync — Accepts a key and Value and sets it to the Cache server.
  3. RefreshAsync — Resets the Sliding Expiration Timer (more about this later in the article) if any.
  4. RemoveAsync — Deletes the cache data based on the key.

Framework provided to implement IDistributedCache

Register an implementation of IDistributedCache in Startup.ConfigureServices. Framework-provided implementations described in this topic include:

  • Distributed Memory Cache
  • Distributed SQL Server cache
  • Distributed Redis cache
  • Distributed NCache cache

Distributed Redis cache

Redis is an open source in-memory data store, which is often used as a distributed cache. You can configure an Azure Redis Cache for an Azure-hosted ASP.NET Core app, and use an Azure Redis Cache for local development.

Redis supports quite lot of data structures like string, hashed, lists, queries and much more and it’s fast key value based database that is written in C. It’s a NoSQL database as well. For this purpose, it is being used in Stackoverflow, Github and so on.

Setting Up Redis

We will see how we can setup Redis in local machine via two approach (Currently I am using Window 10)

1. First Approach by redis-server.exe

  • Run redis-server.exe (Download from Github repo)

    redis-server.exe
     
  • Minimize the Redis-server.exe and open Redis-cli.exe.
     
  • To test, just enter command ping

    Redis ping

2. Second Approach via Chocolatey

Other way to install Redis on a Windows machine is chocolatey. To install chocolatey in a local machine, run the command given below from PowerShell (with administrative mode).

iex ((new-object net.webclient).DownloadString(‘https://chocolatey.org/install.ps1'))

This command downloads the chocalatey installer for Windows and using the command given below, we can install Redis on the local machine.

choco install redis-64

Once Redis Server is installed, use the command given below, where we can start Redis Server

redis-server

Running redis-server

I will use first approach to run server (ie., via redis-server.exe)

Go to the path and open up Powershell and run the following command

By default, Redis runs on the local 6379 port. To change port number

./redis-server --port {your_port}

Once Redis is running at your defined port, the Redis CLI would no longer work. This is because it tries to connect to 6379 by default. To override this, open up PowerShell again and enter the following command

./redis-cli -p {your_port}

Redis CLI Commands

Below are some command which is run on PowerShell.

Redis CLI Commands

Setting a key with expiration time (in seconds) and ttl name is for Time left to expire.

Redis CLI Commands

Steps to integrate Redis cache in ASP.NET Core

Step 1: Make sure redis server is running

./redis-server --port 6000

Step 2: Install package that helps you communicate with the Redis server Microsoft.Extensions.Caching.StackExchangeRedis

Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

Step 3: configure in application to support Redis cache with specific port.

In startup.cs/ConfigureServices method.

ConfigureServices

Step 4: Implementing caching code snippet in Get call of WeatherForeCastController.

WeatherForeCastController

In Line 36, we check if key has a value in Redis, then convert it to a list of Weather list and send back the data and if the value does not exist in Redis, then access the database via efcore (in above code value is hardcoded), get the data and set it to redis.

If key has value then, the data will be stored in Redis as a byte array. We will be converting this array of a string. Which will be converts the string to an object of type, List (Line 38)

DistributedCacheEntryOptions

  1. SetAbsoluteExpiration — Here you can set the expiration time of the cached object.
  2. SetSlidingExpiration — This is similar to Absolute Expiration. It expires as a cached object if it not being requested for a defined amount of time period. Note that Sliding Expiration should always be set lower than the absolute expiration

Summary

In this detailed article, we have seen Distributed Caching, Redis. You can find the completed source code here. I hope you learned something new and detailed in this article. Thanks and happy coding!

Похожее
Dec 21, 2023
Author: Jeremy Wells
Introduction and prerequisites This post is part of an ongoing series where we build a “walking skeleton” application using ASP.NET Core and Angular as well as other technologies for deployment and testing. By now, our application is a minimally functional...
Feb 10, 2023
Author: Abdelmajid BACO
A Quick Guide to Transient, Scoped, and Singleton in C#. In C#, the Transient, Scoped, and Singleton scopes are options for controlling the lifetime of objects which are created by dependency injection. Transient Transient objects are created each time they...
Aug 27
Author: Anton Martyniuk
Multitenancy is a software architecture that allows a single instance of a software application to serve multiple customers, called tenants. Each tenant's data is isolated and remains invisible to other tenants for security reasons. This architecture is commonly used in...
Aug 19
Author: Mukesh Murugan
In this guide, we will learn how to implement Advanced Pagination in ASP.NET Core WebApi with ease. Pagination is one of the most important concepts while building RESTful APIs. You would have seen several public APIs implementing this feature for...
Написать сообщение
Тип
Почта
Имя
*Сообщение