How to use the implementation of distributed cache in ASP. Net Core

  • 2021-11-24 01:17:16
  • OfStack

ASP. Net Core provides several types of caching, including support for distributed caching in addition to in-memory caching and response caching. In the previous article, I discussed ASP. Net Core memory caching. In this article, we will discuss how to use distributed caching in ASP. Net Core, taking Redis and SQL Server as examples.

What is distributed caching

Distributed caching can be used to improve application performance and scalability, Typically distributed caches are shared by multiple application servers, In the distributed cache, the cached data will not fall into the memory of some individual web servers, and these cached data are stored centrally, so that multiple application servers can use them directly. The advantage of this is that if any one server goes down or stops responding, other servers can still retrieve the cached data. Another advantage of distributed caching is that the cached data still exists after the server restarts, and when your application cluster expands, it will not cause any impact on the caching server.

To use distributed caching in ASP. NET Core, the IDistributedCache interface is required, and in the next section, we will discuss the differences between IDistributedCache and IMemoryCache interfaces.

IDistributedCache interface

The IDistributedCache interface used for distributed caching in. Net Core is more complex than the stand-alone IMemoryCache interface. Let's first look at the definition of IMemoryCache interface.

public interface IMemoryCache : IDisposable
  bool TryGetValue(object key, out object value);
  ICacheEntry CreateEntry(object key);
  void Remove(object key);

The IDistributedCache interface is designed for the web farm scenario and includes a set of synchronous and asynchronous methods that can be used for cached Add, Remove, and Retrieve operations. The following is the definition of the IDistributedCache interface.

public interface IDistributedCache
  byte[] Get(string key);
  Task<byte[]> GetAsync(string key);
  void Set(string key, byte[] value, DistributedCacheEntryOptions options);
  Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options);
  void Refresh(string key);
  Task RefreshAsync(string key);
  void Remove(string key);
  Task RemoveAsync(string key);

It is worth noting that the value of the above Set method only supports byte [], which is a bit of a pit. Of course, if you want to plug string, don't worry. ASP. NET Core also provides extension methods to support it.

How to use Redis as a cache medium

The following extension packs can be installed through Nuget with the following code:

Install-Package Microsoft.Extensions.Caching.Redis

In order to be able to use Redis as the application underlying cache, you need to use the AddDistributedRedisCache () extension method. The following code shows how to configure it:

public void ConfigureServices(IServiceCollection services)
   services.AddDistributedRedisCache(option =>
     option.Configuration ="localhost";
     option.InstanceName ="IDG";

How to inject into Controller

The following code listing shows how to inject an IDistributedCache into an Controller and implement inserts and reads from an Redis.

public class DefaultController : Controller
   private readonly IDistributedCache _distributedCache;
   public HomeController(IDistributedCache distributedCache)
     _distributedCache = distributedCache;

   public async Task<string> Get()
     var cacheKey ="IDG";

     var data = _distributedCache.GetString(cacheKey);
     if (!string.IsNullOrEmpty(data))
        return data; //returned from Cache
        string str ="Hello World";
        _distributedCache.SetString(cacheKey, str);
        return str;

How to use SqlServer as a cache medium

To use SqlServer as the underlying cache medium, you need to install the following package through Nuget:

Install-Package Microsoft.Extensions.Caching.SqlServer
Install-Package Microsoft.Extensions.Caching.SqlConfig.Tools

How to make the following configuration in Startup. ConfigureServices ().

    public void ConfigureServices(IServiceCollection services)

      services.AddDistributedSqlServerCache(x =>
        x.ConnectionString = Configuration["ConnectionStrings:Default"];
        x.SchemaName = "dbo";
        x.TableName = "IDGCache";

Next, generate Table in SqlServer to store the cached data by the following command, and the code is as follows:

dotnet sql-cache create <connection string> <schema> <table>

ASP. Net Core provides high-level abstraction of distributed caching. Therefore, no matter whether the underlying cache medium is Redis or SQL Server, the IDistributedCache interface provides a unified and convenient operation of API of Cache, and it is also very convenient for IDistributedCache to be injected into Controller.

Translation link: html

Related articles: