本文主要介紹了緩存的概念,以及如何在服務器內存中存儲內容。今天的目標是利用IDistributedCache來作一些分佈式緩存,這樣咱們就能夠橫向擴展咱們的web應用程序。git
在本教程中,我將使用Redis做爲緩存。Redis是一個可靠的快速內存緩存,能夠存儲多種類型的對象。Redis正在被Twitter, Github, Instagram, Stackoverflow等巨頭使用。github
你能夠在https://github.com/sahan91/DistributedCacheAspNetCoreRedis找到示例代碼。web
這是咱們實現後的一個快照。redis
咱們稱其爲分佈式緩存的主要緣由是,它位於應用服務器以外(與傳統的內存緩存相反),若是須要的話,咱們能夠靈活地水平擴展它(在雲中操做時)。來看看在企業應用程序中是如何有用的。docker
IDistributedCache接口爲咱們提供了一組操做緩存的方法。這裏總結了幾種不一樣的方法。緩存
搭建一個示例應用程序服務器
咱們將用ASP.NET Core 5建立一個Web MVC應用程序。mvc
dotnet new mvc -n DistributedCachedotnet new slndotnet sln add DistributedCache
讓咱們繼續從NuGet添加Redis客戶端包。async
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis --version 5.0.1
建立一個Redis docker容器分佈式
假設已經在你的機器上安裝了Docker。這是很方便的,你能夠在任何想要開發的時候啓動本身的Redis容器。
docker run --name redis-cache -p 5002:6379 -d redis
使用官方的Redis鏡像,建立一個名爲redis-cache的容器,並將容器的6379端口綁定到主機的5002端口。若是你在本地沒有Redis的鏡像,它會從DockerHub獲取它。接下來讓咱們驗證docker實例是否啓動並運行。
docker ps -a
如今咱們已經有了Redis容器並運行,接下來配置咱們的web應用程序。
應用程序配置
由於咱們已經添加了所需的NuGet包,咱們只須要在應用的DI容器中註冊,並告訴它在哪裏能夠找到咱們的Redis實例。
services.AddStackExchangeRedisCache(options =>{ options.Configuration = Configuration.GetSection("Redis")["ConnectionString"]; });
當咱們在服務對象上調用AddStackExchangeRedisCache時,它會在底層經過IDistributedCache接口註冊一個RedisCache類的單例。
services.Add(ServiceDescriptor.Singleton<IDistributedCache, RedisCache>());
由於咱們已經在5002端口上啓動並運行了Docker實例,因此咱們能夠在配置中設置它。
"Redis": { "ConnectionString": "localhost:5002"}
實現
這個功能很簡單,下面是咱們要作的:
UI將相似於如下。
讓咱們看看程序的入口,HomeController類。
public async Task<IActionResult> Index(){ var users = (await _cacheService.GetCachedUser())?.FirstOrDefault(); return View(users); } public async Task<IActionResult> CacheUserAsync(){ var users = await _usersService.GetUsersAsync(); var cacheEntry = users.First(); return View(nameof(Index), cacheEntry); } public IActionResult CacheRemoveAsync(){ _cacheService.ClearCache(); return RedirectToAction(nameof(Index)); }
這裏的代碼很容易解釋,咱們在Index、CacheUserAsync和cacheeremoveasync中實現了以前的3個內容。
跳過全部其餘管道代碼,並展現咱們如何使用Redis緩存獲取和設置值。真正神奇的事情發生在ICacheProvider類中。
在GetFromCache方法中,咱們使用給定的鍵(在本例中爲_Users)調用GetStringAsync。值得注意的是,在將它返回給調用者以前,咱們須要將它反序列化爲咱們想要的類型。相似地,序列化咱們的用戶列表,並將它做爲字符串保存在Redis緩存中的_Users鍵下。
public class CacheProvider : ICacheProvider{ private readonly IDistributedCache _cache; public CacheProvider(IDistributedCache cache) { _cache = cache; } public async Task<T> GetFromCache<T>(string key) where T : class { var cachedResponse = await _cache.GetStringAsync(key); return cachedResponse == null ? null : JsonSerializer.Deserialize<T>(cachedResponse); } public async Task SetCache<T>(string key, T value, DistributedCacheEntryOptions options) where T : class { var response = JsonSerializer.Serialize(value); await _cache.SetStringAsync(key, response , options); } public async Task ClearCache(string key) { await _cache.RemoveAsync(key); } }
咱們能夠鏈接到容器,打開redis-cli查看裏面有什麼。
docker exec -it redis-cache redis-cli
進入後,能夠發出hgetall _Users命令來檢查緩存中有哪些內容。
結論
在本文中,咱們將使用ASP.NET Core提供的IDistributedCache接口,使用Redis做爲後臺存儲。這種方法能夠用來利用Azure Redis緩存等雲服務,用於響應緩存、會話存儲等。
原文連接:https://sahansera.dev/distributed-caching-aspnet-core-redis/