Transfer: ZaraNetcnblogs.com/ZaraNet/p/11837518.html
Hello everyone, today we show how to use Redis in .NET Core, we are going to debate the program is good or bad, want to require a visualization tool, I often use a free tool developed by a large domestic cattle, which Github address: https://github.com/qishibo/AnotherRedisDesktopManager/releases , it really is to force, Redis installed in https://github.com/MicrosoftArchive/redis/releases EasyCaching, I generally use for doing caching abstraction layer, first create a .NET Core API project, then nuget installation EasyCaching.Core and 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(); }
Then in registration middleware Startup, adding EasyCaching first start of service in some option to add EasyCaching to start, you can see AddEasyCaching process is this.
// EasyCaching service collection extensions. public static class EasyCachingServiceCollectionExtensions { public static IServiceCollection AddEasyCaching(this IServiceCollection services, Action<EasyCachingOptions> setupAction); }
The second parameter UseRedis method for which RedisClient instance selection Repository, which is very favorable; we create an API, called RedisController, which our dependency injection service.
[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(); } }
Click Start, access to https: // localhost: port / Redis / Demo , a visualization tool to view and found OK.
Not only how we conducted our assignment, it should also be a need to operate acquired.
[HttpGet("Get")] public IActionResult GetRedisItem() { var item = this.cachingProvider.Get<string>("zaranet use easycaching"); return Ok(item); }
In this way, you can use Redis do you feel valuable thing in the .NET Core, they are very simple things.