
In-memory caching in minimal APIs
ASP.NET Core supplies help for 2 abstractions for working with caching, IMemoryCache and IDistributedCache. Whereas the previous is used to implement in-memory caching, the latter is used to implement distributed caching.
The next use of IMemoryCache reveals how one can retrieve information from the cache if the requested information is accessible. If the information requested just isn’t current within the in-memory cache, the applying will retrieve the information from the information retailer (utilizing a repository), retailer the information within the in-memory cache, and return it.
app.MapGet("authors/getall", (IMemoryCache cache,
IAuthorRepository authorRepository) =>
{
if (!cache.TryGetValue("get-authors",
out Record authors))
{
authors = authorRepository.GetAll();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5))
.SetSlidingExpiration(TimeSpan.FromMinutes(1));
cache.Set("get-authors", authors, cacheEntryOptions);
}
return Outcomes.Okay(authors);
});
As you’ll be able to see within the previous code snippet, the cached content material will reside within the reminiscence for a most of 30 seconds.
Distributed caching in minimal APIs
Distributed caching enhances the efficiency and scalability of purposes by distributing the load throughout a number of nodes or servers. The servers could be positioned both in the identical community or in numerous networks which are unfold throughout geographical distances.
The next code demonstrates tips on how to implement distributed caching in a minimal API endpoint in ASP.NET Core. On this instance, the endpoint returns all writer data from the distributed cache if the information is accessible within the cache. If the requested information just isn’t obtainable within the distributed cache, the endpoint provides the information to the cache after which returns the information.
