In-Memory cache in ASP.NET core

ASP.NET Core provides In-Memory caching to boost our application performance and scalability by storing frequently changing data in the In-Memory cache.

Enable In-Memory caching

To enable In-Memory in ASP.NET core application we need to add the AddMemoryCache() option in ConfigureServices method of Startup class as shown below

public void ConfigureServices(IServiceCollection services)
{
 services.AddOptions();
 services.AddMvc().AddJsonOptions(options =>
 {
  // To override the default camel case conversion in serilization
  options.SerializerSettings.ContractResolver
   = new Newtonsoft.Json.Serialization.DefaultContractResolver();
 });

 // Enable In-Memory cache Service
 services.AddMemoryCache();
}
To work with In-Memory cache, we need to inject the IMemoryCache interface to our class / controller class . It contains some Extension methods to work with In-Memory cache. 

private IMemoryCache cache;

public TestCacheController(IMemoryCache cache)
{
 this.cache = cache;
}

Store a value in the cache

To store an object, we need to use the Set Extension method of IMemoryCache interface.
cache.Set(“AccountId”, accountId);

Retrieve a value from the cache

To retrieve the value from the cache we can use any of the following options

1) Get<T>

Retrieve the value from the cache. It will return null if the value not exists in the cache
int accountId=cache.Get<int>("AccountId”);

2) TryGetValue<T>:

Using this method we can check if the specified key exists in the cache

int accountId;

if(!cache.TryGetValue<int>("AccountId”,out accountId))
{
 return "No value found!";
}
return accountId.ToString();

3) GetOrCreate<T>or GetOrCreateAsync<T>:

Retrive the value from the cache. If the key doesn’t exist, it will add the value to cache

int accountId= cache.GetOrCreate<int>("AccountId”,
   cacheEntry => {
      return 0
      });

This function also have async variant GetOrCreateAsync<T>.

Adding Expiration Policy

While adding the data to the cache, we can choose the expiration policy for it. We have two options for this: Absolute and Sliding

Absolute Expiration

Absolute expiration expires the cache item when the given time has been reached. Giving it a DateTime (or DateTimeOffset) in the future it will expire the item at that point. For setting, we need to use the MemoryCacheEntryOptions

MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions()
{
 AbsoluteExpiration = TimeSpan.FromMinutes(5)
};

cache.Set("AccountId”,2,memoryCacheEntryOptions);
or we can directly use the overload method of Set like

cache.Set("AccountId”,2,DateTimeOffset.UtcNow.AddSeconds(500));

Sliding expiration

Sliding expiration expires the cacheitem if it has not been accessed within the timespan provided. This makes it easy to keep highly used items in cache. 

MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions()
{
 SlidingExpiration = TimeSpan.FromMinutes(ModelConstants.ALLSCRIPTS_TOKEN_EXPIRATION_TIME)
};
cache.Set("AccountId”,2,memoryCacheEntryOptions);
We can also have the following options in MemoryCacheEntryOptions class

1) Priority: It specifies which objects should be removed from the cache as part of reclaim memory policy whenever the web server runs out of memory space. It is of type CacheItemPriority  enum. Possible values are Low, Normal, High, and NeverRemove

2) RegisterPostEvictionCallback: We can register a callback that will execute whenever and item is removed from the cache. 

MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions()
{
 SlidingExpiration = TimeSpan.FromMinutes(ModelConstants.ALLSCRIPTS_TOKEN_EXPIRATION_TIME)
 Priority= CacheItemPriority.Normal;
};
For more information on MemoryCacheEntryOptions check here.

Happy Coding 😊! 

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment