.Net Core 中 MemoryCache 使用


1.Demo,實際項目中不這么使用

class Program
    {
        static void Main(string[] args)
        {
            //緩存的配置
            MemoryCacheOptions cacheOps = new MemoryCacheOptions()
            {
                //緩存最大為100份
                //##注意netcore中的緩存是沒有單位的,緩存項和緩存的相對關系
                SizeLimit = 100,
                //緩存滿了時,壓縮20%(即刪除20份優先級低的緩存項)
                CompactionPercentage = 0.2,
                //兩秒鍾查找一次過期項
                ExpirationScanFrequency = TimeSpan.FromSeconds(3)
            };
            MemoryCache myCache = new MemoryCache(cacheOps);

            //單個緩存項的配置
            MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
            {
                //絕對過期時間1
                //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
                //絕對過期時間2
                //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3),
                //相對過期時間
                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}】");
            });

            myCache.Set("mykey", "myvalue", cacheEntityOps);
            Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey緩存被清除了"}");
            Console.WriteLine("------------------暫停3秒");
            Thread.Sleep(3000);
            Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey緩存被清除了"}");

            Console.ReadKey();
        }
    }
}

 2. 注入(每個要用的Controller 都要構造很麻煩)

Startup.cs

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

HomeController.cs

public class HomeController : Controller
{
    private IMemoryCache _memoryCache;
    public HomeController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }
 
    public IActionResult Index()
    {
        string cacheKey = "key";
        string result;
        if (!_memoryCache.TryGetValue(cacheKey, out result))
        {
            result = $"LineZero{DateTime.Now}";
            _memoryCache.Set(cacheKey, result);
        }
        ViewBag.Cache = result;
        return View();
    }
}
 
protected MemoryCacheEntryOptions EntryOptions
{
    get
    {
        return new MemoryCacheEntryOptions()
        {
            //絕對過期時間1
            //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)),
            //絕對過期時間2
            //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3),
            //相對過期時間
            SlidingExpiration = TimeSpan.FromSeconds(10),
            //優先級,當緩存壓縮時會優先清除優先級低的緩存項
            Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove
                                             //緩存大小占1份
            Size = 1
        };
    }
}


//后面可以加 entryOptions 策略
_memoryCache.Set(cacheKey, result,entryOptions);

 

3.建個共用類

 

public class CacheCenter
{
    public static MemoryCacheProvider MemoryCacheProvider { get; set; }
    
    //.....可加其它類
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    CacheCenter.MemoryCacheProvider = new MemoryCacheProvider();
    
    // Add framework services.   
}

MemoryCacheProvider.cs

public class MemoryCacheProvider
{
//外面可以直接調它
public MemoryCache MemoryCache { get; set; } public MemoryCacheProvider() { MemoryCacheOptions cacheOps = new MemoryCacheOptions() { //緩存最大為100份 //##注意netcore中的緩存是沒有單位的,緩存項和緩存的相對關系 SizeLimit = 100, //緩存滿了時,壓縮20%(即刪除20份優先級低的緩存項) CompactionPercentage = 0.2, //3秒鍾查找一次過期項 ExpirationScanFrequency = TimeSpan.FromSeconds(3) }; MemoryCache = new MemoryCache(cacheOps); } public object Get(string key) { return MemoryCache.Get(key); } public object Set(string key, int seconds) { var options = new MemoryCacheEntryOptions() { //絕對過期時間1 //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)), //絕對過期時間2 //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3), //相對過期時間 SlidingExpiration = TimeSpan.FromSeconds(seconds), //優先級,當緩存壓縮時會優先清除優先級低的緩存項 Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove //緩存大小占1份 Size = 1 }; return MemoryCache.Set(key, options); } }

 

調用


//
設值 if (!CacheCenter.MemoryCacheProvider.MemoryCache.TryGetValue<string>("mykey", out string timestamp)) { CacheCenter.MemoryCacheProvider.Set("mykey", DateTime.Now.ToString(), 3); } //其它地方取值 CacheCenter.MemoryCacheProvider.MemoryCache.Get("mykey")

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM