如何在 ASP.Net Core 中使用 NCache
本文轉(zhuǎn)載自微信公眾號(hào)「碼農(nóng)讀書」,作者碼農(nóng)讀書。轉(zhuǎn)載本文請(qǐng)聯(lián)系碼農(nóng)讀書公眾號(hào)。
雖然 ASP.Net Core 中缺少 Cache 對(duì)象,但它引入了三種不同的cache方式。
- 內(nèi)存緩存
- 分布式緩存
- Response緩存
Alachisoft 公司提供了一個(gè)開源項(xiàng)目 NCache,它是一個(gè)高性能的,分布式的,可擴(kuò)展的緩存框架,NCache不僅比 Redis 快,而且還提供了一些Redis所不具有的分布式特性,如果你想了解 NCache 和 Redis 的異同,可參考如下鏈接:http://www.alachisoft.com/resources/comparisons/redis-vs-ncache.php ,這篇文章我們將會(huì)討論如何在 ASP.Net Core 中使用 NCache。
要想在 ASP.Net Core 中使用 NCache,需要通過(guò) NuGet 安裝如下包,你可以通過(guò) NuGet Package Manager console 窗口輸入如下命令進(jìn)行安裝。
- Install-Package Alachisoft.NCache.SessionServices
使用 IDistributedCache
要想在 ASP.Net Core 中使用分布式緩存,需要實(shí)現(xiàn) IDistributedCache 接口,這個(gè)接口主要用于讓第三方的緩存框架無(wú)縫對(duì)接到 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() 中調(diào)用 AddNCacheDistributedCache 擴(kuò)展方法將其注入到容器中,如下代碼所示:
- // 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 進(jìn)行CURD
為了方便演示,先來(lái)定義一個(gè) Author 類,如下代碼所示:
- public class Author
- {
- public int AuthorId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- }
接下來(lái)實(shí)現(xiàn)從 NCache 中讀取 Author 對(duì)象,如果緩存中存在 Author 對(duì)象,則直接從緩存中讀取,如果緩存中沒有,則需要先從數(shù)據(jù)庫(kù)中獲取 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 世界提供了一種分布式緩存的解決方案,同時(shí)你也能看到 IDistributedCache 是一套標(biāo)準(zhǔn)的用于分布式緩存的高層API,方便第三方的緩存無(wú)縫接入,比如:Redis,Mongodb,Mysql 等等。
譯文鏈接:https://www.infoworld.com/article/3342120/how-to-use-ncache-in-aspnet-core.html