NetCore的緩存使用詳例


關於我

作者博客|文章首發

緩存基礎知識

緩存可以減少生成內容所需的工作,從而顯著提高應用程序的性能和可伸縮性。 緩存最適用於不經常更改的 數據,生成 成本很高。 通過緩存,可以比從數據源返回的數據的副本速度快得多。 應該對應用進行編寫和測試,使其 永不 依賴於緩存的數據。

ASP.NET Core 支持多個不同的緩存。 最簡單的緩存基於 IMemoryCache。 IMemoryCache 表示存儲在 web 服務器的內存中的緩存。 在服務器場上運行的應用 (多台服務器) 應確保會話在使用內存中緩存時處於粘滯狀態。 粘滯會話確保來自客戶端的后續請求都將發送到相同的服務器。

內存中緩存可以存儲任何對象。 分布式緩存接口僅限 byte[] 。 內存中和分布式緩存將緩存項作為鍵值對。

緩存指南

  • 代碼應始終具有回退選項,以獲取數據,而 是依賴於可用的緩存值。
  • 緩存使用稀有資源內存,限制緩存增長:
    • 不要 使用外部 輸入作為緩存鍵。
    • 使用過期限制緩存增長。
    • 使用 SetSize、Size 和 SizeLimit 限制緩存大小]。 ASP.NET Core 運行時不會根據內存 壓力限制緩存 大小。 開發人員需要限制緩存大小。

使用

DI注入

創建一個NetCore控制台項目,進行緩存的項目演示。

控制台項目只有一個初始化的Program.cs文件。基於NetCore進行項目編碼,每一步就是創建一個基礎模板,使用依賴注入的方式。

nuget install Microsoft.Extensions.Hosting
  public static class Program
    {
        static async void Main(string[] args)
        {
           var builder = new HostBuilder().ConfigureServices((context, service) =>
            {

            });

           await builder.RunConsoleAsync();
        }
    }

注入緩存服務,控制台需要下載庫 Microsoft.Extensions.Caching.Memory

nuget install Microsoft.Extensions.Caching.Memory
  public static class Program
    {
        static async void Main(string[] args)
        {
           var builder = new HostBuilder().ConfigureServices((context, service) =>
            {
      		  service.AddMemoryCache();
      		  
              service.AddScoped<CacheService>();//實際測試服務

              service.AddHostedService<BackgroundJob>();//后台執行方法
            });

           await builder.RunConsoleAsync();
        }
    }

后台服務

public class BackgroundJob : IHostedService
    {
        private readonly CacheService _cacheService;

        public BackgroundJob(CacheService cacheService)
        {
            _cacheService = cacheService;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _cacheService.Action();

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }

MemoryCache使用總結

通過構造函數自動注入IMemoryCache

public class CacheService
{
    private readonly IMemoryCache _memoryCache;

    public CacheService(IMemoryCache memoryCache)
    {
   		 _memoryCache = memoryCache;
    }
}

最基本的使用

Set方法根據Key設置緩存,默認緩存不過期

Get方法根據Key取出緩存

/// <summary>
/// 緩存設置
/// </summary>
public void BaseCache()
{
    string cacheKey = "timestamp";
    //set cache
    _memoryCache.Set(cacheKey, DateTime.Now.ToString());

    //get cache
    Console.WriteLine(_memoryCache.Get(cacheKey));
}

IMemoryCache提供一些好的語法糖供開發者使用,具體內容看下方文檔

/// <summary>
/// 特殊方法的使用
/// </summary>
public void ActionUse()
{
    //場景-如果緩存存在,取出。如果緩存不存在,寫入
    //原始寫法
    string cacheKey = "timestamp";
    if (_memoryCache.Get(cacheKey) != null)
    {
        _memoryCache.Set(cacheKey, DateTime.Now.ToString());
    }
    else
    {
        Console.WriteLine(_memoryCache.Get(cacheKey));
    }

    //新寫法
    var dataCacheValue = _memoryCache.GetOrCreate(cacheKey, entry =>
     {
         return DateTime.Now.ToString();
     });
    Console.WriteLine(dataCacheValue);

    //刪除緩存
    _memoryCache.Remove(cacheKey);

    //場景 判斷緩存是否存在的同時取出緩存數據
    _memoryCache.TryGetValue(cacheKey, out string cacheValue);
    Console.WriteLine(cacheValue);

}

緩存過期策略

設置緩存常用的方式主要是以下二種

  1. 絕對到期(指定在一個固定的時間點到期)
  2. 滑動到期(在一個時間長度內沒有被命中則過期)
  3. 組合過期 (絕對過期+滑動過期)

絕對到期

過期策略 5秒后過期

//set absolute cache
string cacheKey = "absoluteKey";
_memoryCache.Set(cacheKey, DateTime.Now.ToString(), TimeSpan.FromSeconds(5));

//get absolute cache
for (int i = 0; i < 6; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheKey));
    Thread.Sleep(1000);
}

滑動到期

過期策略 2秒的滑動過期時間,如果2秒內有訪問,過期時間延后。當2秒的區間內沒有訪問,緩存過期

//set slibing cache
string cacheSlibingKey = "slibingKey";
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.SlidingExpiration = TimeSpan.FromSeconds(2);

_memoryCache.Set(cacheSlibingKey, DateTime.Now.ToString(), options);

//get slibing cache
for (int i = 0; i < 2; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheSlibingKey));
    Thread.Sleep(1000);
}
for (int i = 0; i < 2; i++)
{
    Thread.Sleep(2000);
    Console.WriteLine(_memoryCache.Get(cacheSlibingKey));
}

組合過期

過期策略

6秒絕對過期+2秒滑動過期

滿足任意一個緩存都將失效

string cacheCombineKey = "combineKey";
MemoryCacheEntryOptions combineOptions = new MemoryCacheEntryOptions();
combineOptions.SlidingExpiration = TimeSpan.FromSeconds(2);
combineOptions.AbsoluteExpiration = DateTime.Now.AddSeconds(6);

_memoryCache.Set(cacheCombineKey, DateTime.Now.ToString(), combineOptions);

//get slibing cache
for (int i = 0; i < 2; i++)
{
    Console.WriteLine(_memoryCache.Get(cacheCombineKey));
    Thread.Sleep(1000);
}

for (int i = 0; i < 6; i++)
{
    Thread.Sleep(2000);
    Console.WriteLine(i+"|" + _memoryCache.Get(cacheCombineKey));
}

Console.WriteLine("------------combineKey End----------------");

緩存狀態變化事件

當緩存更新、刪除時觸發一個回調事件,記錄緩存變化的內容。

/// <summary>
/// cache狀態變化回調
/// </summary>
public void CacheStateCallback()
{
    MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
    options.AbsoluteExpiration = DateTime.Now.AddSeconds(3
        );
    options.RegisterPostEvictionCallback(MyCallback, this);

    //show callback console
    string cacheKey = "absoluteKey";
    _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options);

    Thread.Sleep(500);
    _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options);

    _memoryCache.Remove(cacheKey);

}

private static void MyCallback(object key, object value, EvictionReason reason, object state)
{
    var message = $"Cache entry state change:{key} {value} {reason} {state}";
    ((CacheService)state)._memoryCache.Set("callbackMessage", message);

    Console.WriteLine(message);
}

緩存依賴策略

設置一個緩存A
設置一個緩存B,依賴於緩存A 如果緩存A失效,緩存B也失效

/// <summary>
/// 緩存依賴策略
/// </summary>
public void CacheDependencyPolicy()
{
    string DependentCTS = "DependentCTS";
    string cacheKeyParent = "CacheKeys.Parent";
    string cacheKeyChild = "CacheKeys.Child";

    var cts = new CancellationTokenSource();
    _memoryCache.Set(DependentCTS, cts);

    //創建一個cache策略
    using (var entry = _memoryCache.CreateEntry(cacheKeyParent))
    {
        //當前key對應的值
        entry.Value = "parent" + DateTime.Now;

        //當前key對應的回調事件
        entry.RegisterPostEvictionCallback(MyCallback, this);

        //基於些key創建一個依賴緩存
        _memoryCache.Set(cacheKeyChild, "child" + DateTime.Now, new CancellationChangeToken(cts.Token));
    }

    string ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent);
    string ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild);
    string callBackMsg = _memoryCache.Get<string>("callbackMessage");
    Console.WriteLine("第一次獲取");
    Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg);

    //移除parentKey
    _memoryCache.Get<CancellationTokenSource>(DependentCTS).Cancel();
    Thread.Sleep(1000);

    ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent);
    ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild);
    callBackMsg = _memoryCache.Get<string>("callbackMessage");
    Console.WriteLine("第二次獲取");
    Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg);
}

參考資料

AspNetCore中的緩存內存

.NetCore緩存篇之MemoryCache

Asp.Net Core 輕松學-在.Net Core 使用緩存和配置依賴策略

擁抱.NET Core系列:MemoryCache 緩存過期

推薦閱讀

Redis工具收費后新的開源已出現

GitHub上Star最高的工程師技能圖譜

中國程序員最容易發錯的單詞

推薦!!! Markdown圖標索引網站

最后

本文到此結束,希望對你有幫助 😃

如果還有什么疑問或者建議,可以多多交流,原創文章,文筆有限,才疏學淺,文中若有不正之處,萬望告知。

更多精彩技術文章匯總在我的 公眾號【程序員工具集】,持續更新,歡迎關注訂閱收藏。

wechat.png


免責聲明!

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



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