<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          一文看懂ASP.NET Core使用內(nèi)存緩存

          共 7773字,需瀏覽 16分鐘

           ·

          2021-02-01 21:40

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

          • in-memory caching
          • distributed caching
          • response caching

          在本文中,我們來看看如何將那些不易變的數(shù)據(jù)灌到內(nèi)存中實(shí)現(xiàn) ASP.NET Core application 的高性能,然后我會用一些例子來說明這些概念。

          如何啟用 in-memory cache

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


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

          集成好之后,接下來了解一下緩存的統(tǒng)一接口:IMemoryCache ,代碼如下:


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

          那如何在 Controller 中使用呢?可以使用 Controller 的構(gòu)造函數(shù)實(shí)現(xiàn)注入,如下代碼所示:


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

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

          到現(xiàn)在為止,in-memory caching 的配置全部做完,現(xiàn)在可以考慮如何實(shí)現(xiàn)從 Cache 讀取和寫入了。

          Cache的讀取和寫入

          利用 IMemoryCache 接口的 Set () 可實(shí)現(xiàn)向緩存中寫入數(shù)據(jù),請注意這個(gè) Set () 方法接收兩個(gè)參數(shù),第一個(gè)參數(shù)是緩存的名字,第二個(gè)參數(shù)就是你要緩存的內(nèi)容,如下代碼所示:


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

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


                  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();
                  }

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


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

                      return View();
                  }

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

          Cache 的過期策略

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

          要想設(shè)置過期策略,可以通過 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 屬性,它的應(yīng)用場景是這樣的,當(dāng)應(yīng)用程序內(nèi)存不夠時(shí)要回收內(nèi)存的過程中,誰的優(yōu)先級低就會被優(yōu)先移除,除了Normal 枚舉,還有其他諸如:Low, High, NeverRemove ,除了 NeverRemove ,其他的幾種都會被回收機(jī)制管控。

          新的 Cache 機(jī)制還提供了一個(gè)????的方式,那就是 回調(diào)函數(shù) 注入,意味著當(dāng) cache 過期被移除時(shí)會自動觸發(fā)你指定的回調(diào)函數(shù),你可以在 回調(diào)函數(shù) 中做一些你自定義的業(yè)務(wù)邏輯,比如重新給 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();
                  }

          你甚至還可以配置兩個(gè) cache 的依賴關(guān)系,舉個(gè)例子,如果某一個(gè) cache item 被移除了,你希望它關(guān)聯(lián)的 cache 也要自動移除,看起來是不是很 nice,篇幅有限,我會在后面的文章中和大家闡述如何去實(shí)現(xiàn),如果你很想知道,可先參考微軟的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







          回復(fù) 【關(guān)閉】學(xué)關(guān)
          回復(fù) 【實(shí)戰(zhàn)】獲取20套實(shí)戰(zhàn)源碼
          回復(fù) 【被刪】學(xué)個(gè)
          回復(fù) 【訪客】學(xué)
          回復(fù) 【小程序】學(xué)獲取15套【入門+實(shí)戰(zhàn)+賺錢】小程序源碼
          回復(fù) 【python】學(xué)微獲取全套0基礎(chǔ)Python知識手冊
          回復(fù) 【2019】獲取2019 .NET 開發(fā)者峰會資料PPT
          回復(fù) 【加群】加入dotnet微信交流群

          技巧:你真的了解C#中的Math.Round么?


          微信8.0大更新,附最新內(nèi)測版下載地址!


          瀏覽 65
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  91av在线视频会员 | 天天艹天天干 | 俺也去网站 | 天天看天天射 | 亚洲天堂网中文字幕 |