1 緩存基礎知識
緩存是實際工作中非常常用的一種提高性能的方法。
緩存可以減少生成內容所需的工作,從而顯著提高應用程序的性能和可伸縮性。 緩存最適用於不經常更改的數據。 通過緩存,可以比從原始數據源返回的數據的副本速度快得多。
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實例
private IMemoryCache cache;
public CacheController(IMemoryCache cache)
{
this.cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
最后,在Get方法中使用緩存
[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;
}
}
經過測試可以看到,緩存后,我們取到日期就從內存中獲得,而不需要每次都去計算,說明緩存起作用了。