三分鐘學會Redis在.NET Core中作緩存中間件

原文: 三分鐘學會Redis在.NET Core中作緩存中間件

  你們好,今天給你們說明如何在.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 。html

複製代碼
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的過程是這樣的。git

複製代碼
// EasyCaching service collection extensions.
    public static class EasyCachingServiceCollectionExtensions { public static IServiceCollection AddEasyCaching(this IServiceCollection services, Action<EasyCachingOptions> setupAction); }
複製代碼

   UseRedis 方法的第二個參數,適用於Repository的選擇哪一個RedisClient實例,這是很是有利的;咱們建立一個API,名爲 RedisController ,其中依賴注入咱們的服務。github

複製代碼
[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了。redis

 不光如何,咱們咱們進行了賦值,如今應該還須要一個獲取的操做。緩存

複製代碼
[HttpGet("Get")] public IActionResult GetRedisItem() { var item =  this.cachingProvider.Get<string>("zaranet use easycaching"); return Ok(item); }
複製代碼

 就這樣,你就能夠在.NET Core中使用Redis去作你以爲有價值的事情,都是很是簡單的事情。ide

相關文章
相關標籤/搜索