三分鍾學會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 。

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去做你覺得有價值的事情,都是非常簡單的事情。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM