大家好,今天給大家說明如何在.NET Core中使用Redis,我們在想要辯論程式的好與壞,都想需要一個可視化工具,我經常使用的是一位國內大牛開發的免費工具,其Github地址為: https://github.com/qishibo/AnotherRedisDesktopManager/releases ,它真的很給力,Redis的安裝在 https://github.com/MicrosoftArchive/redis/releases,我一般使用的EasyCaching用于做快取抽象層,首先創建一個.NET Core API 專案,隨后nuget安裝 EasyCaching.Core 以及 EasyCaching.Redis ,
public void ConfigureServices(IServiceCollection services) { services.AddEasyCaching(options=> { options.UseRedis(configure => { configure.DBConfig.Endpoints.Add( new EasyCaching.Core.Configurations.ServerEndPoint("localhost",6379) ); configure.DBConfig.AllowAdmin = true; },"RedisExample"); }); services.AddControllers(); }
隨后在Startup中注冊中間件,首先啟動添加EasyCaching的服務,在向啟動添加EasyCaching的某些選項,可以看到AddEasyCaching的程序是這樣的,
// EasyCaching service collection extensions. public static class EasyCachingServiceCollectionExtensions { public static IServiceCollection AddEasyCaching(this IServiceCollection services, Action<EasyCachingOptions> setupAction); }
UseRedis 方法的第二個引數,適用于Repository的選擇哪個RedisClient實體,這是非常有利的;我們創建一個API,名為 RedisController ,其中依賴注入我們的服務,
[Route("/Redis")] [ApiController] public class RedisController : ControllerBase { private IEasyCachingProvider cachingProvider; private IEasyCachingProviderFactory easyCachingProviderFactory; public RedisController(IEasyCachingProviderFactory cachingProviderFactory) { this.easyCachingProviderFactory = cachingProviderFactory; this.cachingProvider = cachingProviderFactory.GetCachingProvider("RedisExample"); } [HttpGet("Demo")] public IActionResult SetRedisItem() { this.cachingProvider.Set("zaranet use easycaching", "this is my value", TimeSpan.FromDays(100)); return Ok(); } }
點擊啟動,訪問到 https://localhost:port/Redis/Demo 中,使用可視化工具查看,發現OK了,

不光如何,我們我們進行了賦值,現在應該還需要一個獲取的操作,
[HttpGet("Get")] public IActionResult GetRedisItem() { var item = this.cachingProvider.Get<string>("zaranet use easycaching"); return Ok(item); }

就這樣,你就可以在.NET Core中使用Redis去做你覺得有價值的事情,都是非常簡單的事情,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/94913.html
標籤:.NET Core
上一篇:樹結構中的左右值計算
