Asp.Net Core中的緩存介紹

一 netcore中緩存相關的類庫都在 Microsoft.Extensions.Caching ,使用MemoryCache首先安裝包html

Install-Package Microsoft.Extensions.Caching.Memory
using Microsoft.Extensions.Caching.Memory;
using System;

namespace 應用程序緩存2
{
    class Program
    {
        static void Main(string[] args)
        {
            //緩存配置
            MemoryCacheOptions options = new MemoryCacheOptions()
            {
                SizeLimit = 100,
                CompactionPercentage = 0.2,
                ExpirationScanFrequency = TimeSpan.FromSeconds(3)
            };
            //內存緩存
            MemoryCache memoryCache = new MemoryCache(options);
            while (true)
            {
                Console.Write("請輸入要緩存的值:");
                string result=Console.ReadLine();

                //單個緩存項的配置
                MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
                {
                    //絕對過時時間
                    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),

                    //相對過時時間
                    //SlidingExpiration = TimeSpan.FromSeconds(3),
                    //優先級,當緩存壓縮時會優先清除優先級低的緩存項
                    Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
                                                     //緩存大小佔1份
                    Size = 1
                };
                cacheEntityOps.RegisterPostEvictionCallback((key, value, reason, state) => {
                    Console.WriteLine($"回調函數輸出【鍵:{key},值:{value},被清除的緣由:{reason}】");
                });  
                //檢查是否存在Name的緩存
                object cached;
                bool res= memoryCache.TryGetValue("name",out cached);
                if (!res)
                {
                    Console.WriteLine("檢查到不存在緩存");
                    memoryCache.Set("name", result, cacheEntityOps);
                }
                else
                {
                    Console.WriteLine($"name緩存的結果是{cached}");
                }
                Console.ReadKey();
            }
        }
    }
}

參考 https://www.cnblogs.com/wyy1234/p/10519681.html緩存

相關文章
相關標籤/搜索