Skip to content

Distributed URP cache in ASP.NET Core

Pratik Bhattacharya edited this page Apr 18, 2021 · 2 revisions

ASP.NET Core provides an IDistributedCache interface for ASP.NET Core apps to use a Distributed cache. URP has its implementation of IDistributedCache, which can be used in an ASP.NET Core Web Application. The Distributed URP implementation allows the distributed Cache to use a URP Redis Cache cluster as its backend store. See ASP.NET Core's official documentation to read more about IDistributedCache.

Installation

Install the package DistributedCache.Extensions.UnifiedRedisPlatform from the global NuGet feed

Install-Package DistributedCache.Extensions.UnifiedRedisPlatform

Registration

You must register the URP Distributed Cache in Startup.cs under ConfigureServices method

services.AddUnifiedRedisPlatform(options =>
{
    options.Cluster = Configuration.GetValue<string>("URP:Cluster");
    options.Application = Configuration.GetValue<string>("URP:Application");
    options.AppSecret = Configuration.GetValue<string>("URP:ApplicationSecret");
    options.PreferredLocation = Configuration.GetValue<string>("URP:Location");
});
  1. Cluster: This is the Cluster ID under which the Application has been registered.
  2. Application: This is a unique ID of your Application
  3. AppSecret: Application secret for authenticating the calls
  4. PreferredLocation: The location parameter is required to get the Redis Cache located closest to the Client Application. The Location of the client application can either be specified when connecting to the Cluster. If left blank, then the Location is auto-detected.

Usage

The URP Distributed Cache implements all the methods provided by IDistributedCache. See here to get the complete list of methods exposed by IDistributedCache.

After you have completed the registration, IDistributedCache can be injected into any of the services.

    [ApiController]
    [Route("api/cache")]
    public class CacheController : ControllerBase
    {
        private readonly IDistributedCache _cache;

        public CacheController(IDistributedCache cache)
        {
            _cache = cache;
        }

        [HttpPost]
        [Route("keys")]
        public async Task<IActionResult> Set([FromBody]CachedObject obj)
        {
            if (obj.Options == null)
                await _cache.SetAsync(obj.Key, Encoding.ASCII.GetBytes(obj.Value));
            else
                await _cache.SetStringAsync(obj.Key, obj.Value, new DistributedCacheEntryOptions 
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(obj.Options.AbsoluteExpiration),
                        SlidingExpiration = TimeSpan.FromSeconds(obj.Options.SlidingWindow)
                    });
            return new CreatedResult("Get", obj.Key);
        }

        [HttpGet]
        [Route("keys/{key}")]
        public async Task<IActionResult> Get([FromRoute] string key)
        {
            var value = await _cache.GetAsync(key);
            if (value == null)
                return new NotFoundResult();
            return new OkObjectResult(Encoding.ASCII.GetString(value));
        }
    }

Additional Methods

The above registration will also register the interface IDistributedUnifiedRedisCache. Using this interface, you can utilize the additional methods of URP. As of today, the following methods are available:

  1. Task<IEnumerable<RedisKey>> GetKeys(string pattern = "") - Used to get all keys from URP matching the given pattern. The pattern accepts wildcard character '*'.
Clone this wiki locally