ASP.NET Core 記憶體快取示範(Microsoft.Extensions.Caching.Memory)

平時大多數資料都是儲存在資料庫中,為了降低資料庫的存取次數導致資料庫負荷過大,讓每個回應都有較大的延遲,我們通常會把常用的資料儲存在快取中,再定時的去更新,除了降低資料庫的存取次數外,還可以加快回應速度。
快取最主要可以區分為集中式和分散式,最常見的分法就是集中式是只有一個主機,而分散式則是可以讓多台主機存取。我們這次要使用的 Microsoft.Extensions.Caching.Memory 套件是微軟官方的集中式快取,將快取資料儲存在記憶體中。

安裝

先使用 NuGet 安裝 Microsoft.Extensions.Caching.Memory 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Microsoft.Extensions.Caching.Memory
    

註冊服務

需要先在 Program.cs 中註冊服務
    
builder.Services.AddMemoryCache();

var app = builder.Build();
    

使用示範

這裡建立了一個 API Controller ,在 Get 中有找到快取就會回傳內容,沒有則回傳 404。在 Set 中可以設定快取,可以使用 SecondsToExpire 參數指定快取過期時間。最後 Delete 則是刪除快取。
    
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly IMemoryCache _memoryCache;

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

    [HttpGet("{key}")]
    public ActionResult Get(string key)
    {
        var hasCache = _memoryCache.TryGetValue(key, out string? value);
        // 如果沒有快取就回傳 404
        if (!hasCache) return NotFound();

        return Ok(
            new
            {
                key,
                value
            }
        );
    }
    
    public class SetRequestBody
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public int? SecondsToExpire { get; set; }
    }

    [HttpPost]
    public ActionResult Set([FromBody] SetRequestBody body)
    {
        if (body.SecondsToExpire.HasValue)
        {
        	// 設定快取和指定過期時間
            _memoryCache.Set(body.Key, body.Value, TimeSpan.FromSeconds(body.SecondsToExpire.Value));
        }
        else
        {
        	// 設定快取(沒有過期時間)
            _memoryCache.Set(body.Key, body.Value);
        }

        return Ok();
    }
    
    [HttpDelete("{key}")]
    public ActionResult Delete(string key)
    {
    	// 刪除快取
        _memoryCache.Remove(key);
        return Ok();
    }
}
    



參考資料:
Microsoft.Learn - Caching in .NET

留言