如何在 ASP.Net Core 使用 分佈式緩存

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<stringGet()
     {
          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.SqlServer
Install-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/article/3262990/web-development/how-to-implement-a-distributed-cache-in-aspnet-core.html


本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章