如何使用內存緩存(IMemoryCache)

1 緩存基礎知識

緩存是實際工做中很是經常使用的一種提升性能的方法。api

緩存能夠減小生成內容所需的工做,從而顯著提升應用程序的性能和可伸縮性。 緩存最適用於不常常更改的數據。 經過緩存,能夠比從原始數據源返回的數據的副本速度快得多。緩存

2 使用內存緩存(IMemoryCache)

首先,咱們簡單的建立一個控制器,實現一個簡單方法,返回當前時間。咱們能夠看到每次訪問這個接口,均可以看到當前時間。函數

[Route("api/[controller]")]
[ApiController]
public class CacheController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        return DateTime.Now.ToString();
    }
}

而後,將Microsoft.Extensions.Caching.Memory的NuGet軟件包安裝到您的應用程序中。性能

Microsoft.Extensions.Caching.Memory

接着,使用依賴關係注入從應用中引用的服務,在Startup類的ConfigureServices()方法中配置:測試

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

接着,在構造函數中請求IMemoryCache實例this

private IMemoryCache cache;
public CacheController(IMemoryCache cache)
{
    this.cache = cache ?? throw new ArgumentNullException(nameof(cache));
}

最後,在Get方法中使用緩存code

[HttpGet]
public string Get()
{
    //讀取緩存
    var now = cache.Get<string>("cacheNow");
    if (now == null) //若是沒有該緩存
    {
        now = DateTime.Now.ToString();
        cache.Set("cacheNow", now);
        return now;
    }
    else
    {
        return now;
    }
}

通過測試能夠看到,緩存後,咱們取到日期就從內存中得到,而不須要每次都去計算,說明緩存起做用了。接口

相關文章
相關標籤/搜索