如何在 ASP.Net Core 中使用 NCache
本文轉載自微信公眾號「碼農讀書」,作者碼農讀書。轉載本文請聯系碼農讀書公眾號。
雖然 ASP.Net Core 中缺少 Cache 對象,但它引入了三種不同的cache方式。
- 內存緩存
- 分布式緩存
- Response緩存
Alachisoft 公司提供了一個開源項目 NCache,它是一個高性能的,分布式的,可擴展的緩存框架,NCache不僅比 Redis 快,而且還提供了一些Redis所不具有的分布式特性,如果你想了解 NCache 和 Redis 的異同,可參考如下鏈接:http://www.alachisoft.com/resources/comparisons/redis-vs-ncache.php ,這篇文章我們將會討論如何在 ASP.Net Core 中使用 NCache。
要想在 ASP.Net Core 中使用 NCache,需要通過 NuGet 安裝如下包,你可以通過 NuGet Package Manager console 窗口輸入如下命令進行安裝。
- Install-Package Alachisoft.NCache.SessionServices
使用 IDistributedCache
要想在 ASP.Net Core 中使用分布式緩存,需要實現 IDistributedCache 接口,這個接口主要用于讓第三方的緩存框架無縫對接到 ASP.Net Core 中,下面是 IDistributedCache 的骨架代碼。
- namespace Microsoft.Extensions.Caching.Distributed
- {
- public interface IDistributedCache
- {
- byte[] Get(string key);
- void Refresh(string key);
- void Remove(string key);
- void Set(string key, byte[] value,
- DistributedCacheEntryOptions options);
- }
- }
配置 NCache
要想把 NCache 作為分布式緩存,需要在 ConfigureServices() 中調用 AddNCacheDistributedCache 擴展方法將其注入到容器中,如下代碼所示:
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddNCacheDistributedCache(configuration =>
- {
- configuration.CacheName = "IDGDistributedCache";
- configuration.EnableLogs = true;
- configuration.ExceptionsEnabled = true;
- });
- services.AddControllersWithViews();
- }
使用 NCache 進行CURD
為了方便演示,先來定義一個 Author 類,如下代碼所示:
- public class Author
- {
- public int AuthorId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- }
接下來實現從 NCache 中讀取 Author 對象,如果緩存中存在 Author 對象,則直接從緩存中讀取,如果緩存中沒有,則需要先從數據庫中獲取 Author,然后再將 Author 塞入到 Cache 中,下面的具體代碼邏輯僅供參考。
- public async Task<Author> GetAuthor(int id)
- {
- _cache = NCache.InitializeCache("CacheName");
- var cacheKey = "Key";
- Author author = null;
- if (_cache != null)
- {
- author = _cache.Get(cacheKey) as Author;
- }
- if (author == null) //Data not available in the cache
- {
- if (_cache != null)
- {
- _cache.Insert(cacheKey, author, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), Alachisoft.NCache.Runtime.CacheItemPriority.Default);
- }
- }
- return author;
- }
NCache 由 Alachisoft 出品給 .NET 世界提供了一種分布式緩存的解決方案,同時你也能看到 IDistributedCache 是一套標準的用于分布式緩存的高層API,方便第三方的緩存無縫接入,比如:Redis,Mongodb,Mysql 等等。
譯文鏈接:https://www.infoworld.com/article/3342120/how-to-use-ncache-in-aspnet-core.html


















