如何在 ASP.Net Core 使用 內存緩存

ASP.NET Core 是一個輕量級,模塊化的框架,常用來在 Windows,Linux 和 MacOS 上構建高性能,現代化的web框架,不像過去的 Asp.NET,在 ASP.NET Core 中並沒有內置 Cache 對象,不過你可以通過 nuget 上的擴展實現如下三種 cache:

  • in-memory caching

  • distributed caching

  • response caching

在本文中,我們來看看如何將那些不易變的數據灌到內存中實現 ASP.NET Core application 的高性能,然後我會用一些例子來說明這些概念。

如何啓用 in-memory cache

要想將 in-memory cache 集成到 ASP.NET Core 中,就需要將其注入到 ServiceCollection 容器,如下代碼所示:


public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddMemoryCache();
}

集成好之後,接下來了解一下緩存的統一接口:IMemoryCache ,代碼如下:


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

那如何在 Controller 中使用呢?可以使用 Controller 的構造函數實現注入,如下代碼所示:


    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private IMemoryCache cache;

        public HomeController(ILogger<HomeController> logger, IMemoryCache cache)
        {
           _logger = logger;
        }
    }

到現在爲止,in-memory caching 的配置全部做完,現在可以考慮如何實現從 Cache 讀取和寫入了。

Cache的讀取和寫入

利用 IMemoryCache 接口的 Set<T>() 可實現向緩存中寫入數據,請注意這個 Set<T>() 方法接收兩個參數,第一個參數是緩存的名字,第二個參數就是你要緩存的內容,如下代碼所示:


        public IActionResult Index()
        {
            cache.Set("IDGKey", DateTime.Now.ToString());
            return View();
        }

從 Cache 中提取內容,需要使用 IMemoryCache 接口的 TryGet() 方法,下面是對 Index 方法的一個修改版本,代碼如下:


        public IActionResult Index()
        {
            string key = "IDGKey";

            string obj;
            if (!cache.TryGetValue<string>(key, out obj))
            {
                obj = DateTime.Now.ToString();
                cache.Set<string>(key, obj);
            }

            ViewBag.Cache = obj;

            return View();
        }

還有一個叫做 GetOrCreate 方法,從名字上就能看出來,如果獲取不到就會創建一個,如下代碼所示:


        public IActionResult Index()
        {
            cache.GetOrCreate<string>("IDGKey", cacheEntry =>
            {
                return DateTime.Now.ToString();
            });

            return View();
        }

對了,除了同步版本的 GetOrCreate,還有一個支持異步的 GetOrCreateAsync

Cache 的過期策略

可以對緩存數據指定過期策略,比如說:絕對過期時間滑動過期時間,前者表示緩存數據的絕對存活時間,時間一到就會立即移除,後者表示指定的時間間隔內數據沒有被訪問到,那麼就會被移除,如果不明白的化,參考 Session 的過期機制。

要想設置過期策略,可以通過 MemoryCacheEntryOptions 類來配置,如下代碼所示:


        public IActionResult Index()
        {
            MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();

            cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);

            cacheExpirationOptions.Priority = CacheItemPriority.Normal;

            cache.Set<string>("IDGKey", DateTime.Now.ToString(), cacheExpirationOptions);

            return View();
        }

值得注意的是上面的 Priority 屬性,它的應用場景是這樣的,當應用程序內存不夠時要回收內存的過程中,誰的優先級低就會被優先移除,除了Normal 枚舉,還有其他諸如:Low, High, NeverRemove ,除了 NeverRemove ,其他的幾種都會被回收機制管控。

新的 Cache 機制還提供了一個????????的方式,那就是 回調函數 注入,意味着當 cache 過期被移除時會自動觸發你指定的回調函數,你可以在 回調函數 中做一些你自定義的業務邏輯,比如重新給 cache 注入值,如下代碼所示:


        public IActionResult Index()
        {
            MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();

            cacheExpirationOptions.RegisterPostEvictionCallback((obj1, obj2, reason, obj3) =>
            {
                //callback

            }, this);

            cache.Set<string>("IDGKey", DateTime.Now.ToString(), cacheExpirationOptions);

            return View();
        }

你甚至還可以配置兩個 cache 的依賴關係,舉個例子,如果某一個 cache item 被移除了,你希望它關聯的 cache 也要自動移除,看起來是不是很 nice,篇幅有限,我會在後面的文章中和大家闡述如何去實現,如果你很想知道,可先參考微軟的MSDN:https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-5.0

譯文鏈接:https://www.infoworld.com/article/3230129/how-to-use-in-memory-caching-in-aspnet-core.html?nsdr=true

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