在ASP.NET Core 2.0中使用MemoryCache

來源:互聯網
上載者:User

標籤:configure   2.0   ice   tar   caching   .net   tps   images   需要   

說到記憶體緩衝大家可能立馬想到了HttpRuntime.Cache,它位於System.Web命名空間下,但是在ASP.NET Core中System.Web已經不複存在。今兒個就簡單的聊聊如何在ASP.NET Core中使用記憶體緩衝。我們一般將經常訪問但是又不是經常改變的資料放進緩衝是再好不過了,這樣可以明顯提高應用程式的效能。關於MemoryCache在Github上的地址:https://github.com/aspnet/Caching 總共有4個項目

第一個項目是緩衝的抽象,其他三個是不同的類型Memory,Redis,SqServer

首先需要在ConfigureServices中註冊快取服務

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

在下面的代碼中從Home控制器的構造函中擷取IMemoryCache執行個體

public class HomeController : Controller{    private IMemoryCache _cache;    public HomeController(IMemoryCache memoryCache)    {        _cache = memoryCache;    }}

關於緩衝的使用常用的就是Set Get Remove,有人喜歡把這些代碼封裝到單獨的類庫中,我覺得沒有必要,它可以直接在我們的Web項目中直接使用,而且IMemory向外的提供的擴充方法就是最好的封裝

設定緩衝 Set

_cache.Set("key", "value");

擷取緩衝 Get

var result = _cache.GetOrCreate("myKey", (entry) =>{    entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120);    return DateTime.Now.ToString();});

 移除緩衝 Remove

_cache.Remove("key");

 

在ASP.NET Core 2.0中使用MemoryCache

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.