ASP.Net Core 提供了多种类型的缓存,除了内存缓存响应缓存之外,还提供了对 分布式缓存 的反对。在之前的一篇文章中,我探讨了 ASP.Net Core 的内存缓存。在本文中,咱们将探讨如何在 ASP.Net Core 中应用分布式缓存,本篇就拿 Redis 和 SQL Server 作为演示。

什么是分布式缓存

分布式缓存 可用于进步应用程序的性能和可伸缩性,通常 分布式缓存 被多个应用服务器共享,在分布式缓存中,缓存的数据不会落在某些个别的web服务器内存中,这些缓存数据采纳集中化存储,这样多个应用服务器都能够间接应用,这样做的益处在于,如果任何一个服务器宕机或者进行响应,其余的服务器依然可能检索缓存的数据。分布式缓存的另一个长处是,缓存的数据在服务器重启后依然存在,当你的利用集群扩大时,并不会对缓存服务器造成任何影响。

要想在 ASP.NET Core 中应用分布式缓存,须要用到 IDistributedCache 接口,在下一节中,咱们将会一起探讨 IDistributedCache 和 IMemoryCache 接口的区别。

IDistributedCache 接口

在.Net Core 中用于分布式缓存的 IDistributedCache 接口要比 单机版的 IMemoryCache 接口更简单,先来看一下 IMemoryCache 接口定义。

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

IDistributedCache 接口是为 web farm 场景设计的, 它蕴含了一组同步和异步办法,可用于对缓存的 Add,Remove,Retrieve 操作,上面是 IDistributedCache 接口的定义。

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);}

有一点值得注意,下面的 Set 办法的 value 仅反对 byte[],有点坑哈,当然你要塞入 string 的话, 不必放心,ASP.NET Core 也提供了扩大办法对其进行反对.

如何应用 Redis 作为缓存介质

能够通过 Nuget 来装置如下扩大包,代码如下:

Install-Package Microsoft.Extensions.Caching.Redis

为了可能把 Redis 作为利用底层缓存,须要应用 AddDistributedRedisCache() 扩大办法,上面的代码展现了如何去配置:

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

如何注入到 Controller

上面的代码清单展现了如何将 IDistributedCache 注入到 Controller 中并实现从 Redis 中进行插入和读取。

public class DefaultController : Controller{     private readonly IDistributedCache _distributedCache;          public HomeController(IDistributedCache distributedCache)     {          _distributedCache = distributedCache;     }     [HttpGet]     public async Task<string> Get()     {          var cacheKey ="IDG";          var data = _distributedCache.GetString(cacheKey);                    if (!string.IsNullOrEmpty(data))          {               return data; //returned from Cache          }          else          {               string str ="Hello World";               _distributedCache.SetString(cacheKey, str);               return str;          }     }}

如何应用 SqlServer 作为缓存介质

要想将 SqlServer 作为底层的缓存介质,须要通过 Nuget 装置如下包:

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

如何在 Startup.ConfigureServices() 中做如下配置。

        public void ConfigureServices(IServiceCollection services)        {            services.AddControllersWithViews();            services.AddDistributedSqlServerCache(x =>            {                x.ConnectionString = Configuration["ConnectionStrings:Default"];                x.SchemaName = "dbo";                x.TableName = "IDGCache";            });        }

接下来通过如下命令在 SqlServer 中生成 Table 来寄存缓存数据,代码如下:

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

ASP.Net Core 提供了分布式缓存的高层形象。因而,无论底层缓存介质是 Redis 还是 SQL Server, IDistributedCache接口都提供了对立并且便捷的操控Cache的API,而且 IDistributedCache 注入到 Controller 中也是十分不便的。

译文链接:https://www.infoworld.com/art...

更多高质量干货:参见我的 GitHub: csharptranslate