Introduction
In this article, we are going to learn about caching techniques and how to implement them in Azure Cloud. For example, we have a web application that is hosted on the server. Now, the users trying to use that are sending the request to the app server and the request will call the database to get the data when the user reads and writes the data from and to the database.
Most of the time, users will interact with the database to read and write the object. Mostly, reading from and writing to the database will take some time to complete the operation because when they are reading the data from the database, the application has to execute the queries to get the desired information. Similar things happen when writing data to the database and the data may need to be updated in multiple tables. Also, the indexes should get updated properly.
Normally, data is stored on local disks in the database server. When a user requests data, the same needs to be populated from the disk and should be available in memory. Now, when we implement caching, the disk space will act as the database to store the data on it and the data will be always available in memory, so the data retrieval would be very fast. The Cached data will be stored in the key-value pair so the users don’t have to execute complex queries to get the data.
Redis Cache Features
- Increases application performance
- Increases availability (Geo-Replication)
- Provides in-memory data
- Fully managed by Azure and based on the open-source Data Backups
- Stores data in - Strings (max 521 MB), Hashes (unordered), Lists (ordered by sequence), and Sets (only unique values)
Keys to remember
- Store simple data that is needed very often
- Set the right policies to delete/update when it is required
- Pre-populate the cache data
Implement Azure Redis Cache in the portal
Step 1
Log in to the
Azure portal by using your credentials. Go to the marketplace and search for Azure Redis Cache.
- DNS Name - Enter the unique name
- Subscription - Choose your subscription
- Resource group - Create new/choose an existing one from the dropdown value
- Location - Choose your location
- Pricing tier - In Azure, there are 3 types of tiers available, i.e., Basic, Standard, Premium. For this demo, I am using the basic tier because -
- Basic tier comes with shared service
- SSL supports by default, but we can change later if we don’t want.
- Normally used for the development phase
- Standard and Premium
- Come with 99.9% SLA
- Dedicated service
- Redis cluster
- Data Persistence
- Virtual network
Step 2
Once the deployment is done, open the Redis Cache window. The SSL port is disabled by default.
Schedule updates feature will allow us to configure the timeframe within which Azure should provide the update. This allows planning the maintenance so that the availability is optimized.
Import and Export Data allows us to export the data to another cache or pre-populate your cache. If the cache fails for any reason, the cache data will be rebooted from there.
Access Keys - we will be getting the connecting string in order to connect the Azure Redis Cache from our web application or other apps.
Cache Invalidation
So, we have a cache object that will store cookie data. In some scenarios, we may need to update the cached information frequently, i.e., we need to remove the existing cached information and update the same with new values. When a user requests the data, then the application gets the data from the database if cache data is not available. We can invalidate the cache in many ways. The most common approaches are - delete the cache in the application side or set absolute expiration.
Implementing Azure Redis Cache in ASP.NET Core Application
Step 3
Download the sample application available in this demo. We have created a web app that will load images from the database.
Step 4
Add a reference to “Microsoft.Extensions.Caching.Redis.Core” from NuGet Package Manager and click the "Install" button.
Step 5
Add the below-mentioned dependency injection in your Startup.cs file.
- services.AddDistributedRedisCache(options =>
- {
- options.Configuration = Configuration.GetConnectionString("RedisConnectionString");
- options.InstanceName = "master";
- });
Step 6
Get Azure connection from the portal under Access Keys feature and add it in the appsettings.json file “RedisConnectionString”.
Step 7
Add the IDistributedCache reference into the controller class.
Step 8
Add a reference to “Newtonsoft.Json” from NuGet Package Manager and click the "Install" button.
Step 9
Create a Controller class “CookiesDemoController.cs” and method to populate the data from the database.
Step 10
Create an MVC View to populate the data from the controller methods.
Step 11
Run the application. On every page load, the controller method will read the cached object. If the requested data is not available in the cache, then the request will hit the database and will load the data. Once the load is loaded from the database, then we are setting up the cache object to store the data which comes from the database. The second time when we will call the same method, the system will read cached data and render to the UI instead of hitting the database.
_cache.SetString("Cookies", JsonConvert.SerializeObject(cookiesDemo));
Sample Code
- public IActionResult Index() {
-
- List < CookiesDemo > cookiesDemo = new List < CookiesDemo > ();
- var cachedObj = _cache.GetString("Cookies");
- if (string.IsNullOrEmpty(cachedObj)) {
- cookiesDemo = _AppDBContext.CookiesDemo.ToList();
- _cache.SetString("Cookies", JsonConvert.SerializeObject(cookiesDemo));
- } else {
-
- cookiesDemo = JsonConvert.DeserializeObject < List < CookiesDemo >> (cachedObj);
- }
- DemoViewmodel modelObj = new DemoViewmodel();
- modelObj.CookiesDemo = cookiesDemo;
- return View(modelObj);
- }
Loading from database without cache
SQL Table
- CREATE TABLE CookiesDemo (
- ID INT identity (1,1),
- CookieName VARCHAR(100),
- FilePath VARCHAR(500)
- )
Summary
In this article, we have learned how to implement Azure Redis Cache. Also, we looked into the feature and options of Azure Redis Cache available in the Azure portal.
We have created a web application that will get the data from the database only when cached information is not available in memory.