What is Caching and How does It Work?

27 October 2021 at 22:00 by ParTech Media - Post a comment

Very often we deal with a lot of repetitive data that does not change frequently. For example, consider a form filled by a user which asks for address details. The form will have a list of countries, states, and cities as part of it. These data usually never change.

Also, there are possibilities that this data might be obtained from a third-party entity that maintains this generic data. They will provide it for a fee. In such cases, every time the data is fetched from a third-party entity, you will be charged. In such cases, storing the data somewhere temporarily and using it later will reduce the number of hits to the third-party entity, saving you cost and at the same time offering improved performance.

Here’s another scenario - there could be times when users visit a page, close it, and then again visit it immediately for some other reason. In such cases, the data for the page need not be fetched again from the backend. Rather it can be stored somewhere temporarily and reused.

In both these scenarios, data in a different form that was fetched earlier is being reused in the subsequent requests. This concept is known as Caching. Let's understand a bit more about caching in this post.

Table of contents

  1. What is caching?
  2. Types of caching,
  3. Sample caching in .Net
  4. Conclusion

What is Caching?

Caching is the process of storing frequently accessed information in the memory so that it can be retrieved and used directly from the memory (rather than accessing it from its source). This gives you an upper hand in performance and scalability. Also, it's handy when the source is down and information is required for processing information..Net provides caching functionality for Windows-based server applications and ASP. Net applications.

Types of caching

Output cache

Output cache comes into the picture whenever we discuss ASP. Net MVC-based applications. It helps in improving the performance of the web application by caching the output of the action method in the controller.

For example, an ASP .Net MVC application displays a list of data fetched from a database. So, every time a page loads, the data is fetched. The performance of the application can be improved by caching the data returned from the action method by the Output cache.

Data cache

Data cache is a basic caching type in which the data that has to be accessed multiple times is stored in the cache. And when the cache period expires, the data is again fetched from the source and stored in the cache.

Typical examples would be storing a token to access third-party API calls (where the token once fetched is added to the cache and refreshed only after a certain period).

Object cache

Object cache provides the ability to store any time of the object in the cache with a specific key for it. The object can be a data type, web control, class dataset object, etc..,

Configuration cache

Values that can be frequently modified or that need to be changed without any code changes are being put in the configuration file. Configuration cache stores the configuration information in the server memory

Sample caching in .Net

Let's understand how caching works with a simple example. To illustrate this, we are going to create a memory cache in an ASP .Net Core Web API.

First, create a new ASP. Net Core Web API project and provide a valid name for the solution. Don’t forget to choose the required version of .Net

Once the solution is created, it will look like the below structure.

Now, we are going to make use of the memory cache to store the data. To do that, the memory cache has to be injected into the Startup so that it will be available throughout the application.

Add - services.AddMemoryCache(); in the method - ‘ConfigureServices’ which will be used throughout the application.

Now that the memory cache is injected, let's use them in the Controller. In the default project template, there will be WeatherForecastController. By default, the controller is written with a default get return type. Create a global variable having scope within the controller and of type memory cache.

Use the constructor injection of the memory cache using the reference -

using Microsoft.Extensions.Caching.Memory;
private readonly IMemoryCache _memoryCache;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IMemoryCache memoryCache)

​    {
​      _logger = logger;
​      _memoryCache = memoryCache;
​    }

Once the memory cache is injected and assigned, the cache object can be used to store the data. Following is a sample code that can be used to store the data.

 if (!_memoryCache.TryGetValue("test", out string value))
​      {
​        var cacheExpiryOptions = new MemoryCacheEntryOptions
​        {
​          AbsoluteExpiration = DateTime.Now.AddMinutes(30)
​        };

​        _memoryCache.Set("test", "TestValue", cacheExpiryOptions);
​      }

The first condition validates whether the cache key - ‘test’ has any day stored in the cache. If yes, it will be pulled and stored in the variable value and the code will skip the code inside the if condition.

In case if the cache key has no data in the memory, then the expiry options object is initialized with some configured values. Post this, the cache key, its value, and the expiry options are set.

The key and value can be valid information that is fetched from a database, third-party APIs, and so on. Since memorycache is used, data of any type can be stored in it. Also, it takes the key of the type object and the value of the type object.

Conclusion

In this post, we have seen the different types of cache and a sample example on how to implement a cache in an ASP .Net Core Web API project. In our next post, we will see more about output cache and a way to implement it in .Net.

Latest