this article, we will see how to use Azure Redis cache to cache your data and provide a faster way of loading the web pages to the users.
What is the Azure Redis cache?
Azure Redis Cache is based on the popular open source Redis cache. It gives you access to a secure, dedicated Redis cache, managed by Microsoft and accessible from any application within Azure.
Why would I use the Azure Redis Cache?
Azure Redis Cache helps your application become more responsive even as the customer load increases. It takes advantage of the low-latency, high-throughput capabilities of the Redis engine. This separate, distributed cache layer allows your data tier to scale independently for more efficient use of the compute resources in your application layer.
Let's go to the best part.. follow these steps to reproduce:
First, you must have your Azure Redis Cache set up.
Wait until it finishes deploying (it takes some minutes, do not worry).
Now, create a new MVC ASP.NET Core project and install the NuGet package: Microsoft.Extensions.Caching.Redis.Core
- With your environment and the Redis cache ready, let's start configuring your project with the settings from the Redis cache in order to make them communicate. First, get the Redis cache connection string from the Redis Cache panel.
- Update your appsettings.json to add the connection string from your Redis Cache.
- "ConnectionStrings": {
- "RedisConnection": "TVtesting.redis.cache.windows.net:6380,password=XXXXXXXXXXXXXXXX,ssl=True,abortConnect=False" }
- Update your Startup class in the ConfigureServices method.
- public void ConfigureServices(IServiceCollection services) {
-
- services.AddMvc();
- services.AddDistributedRedisCache(options => {
- options.Configuration = Configuration.GetConnectionString("RedisConnection");
- options.InstanceName = "TVTesting";
- });
- }
Update your Controller constructor to receive the cache object passed by dependency injection and use your cache object to set and get the cached data.
- public class HomeController: Controller {
- private IDistributedCache _cache;
- public HomeController(IDistributedCache cache) {
- this._cache = cache;
- }
- public IActionResult Index() {
- string test = _cache.GetString("Test") ? ? "";
- if (string.IsNullOrEmpty(test)) {
- _cache.SetString("Test", "Tested");
- test = _cache.GetString("Test") ? ? "";
- }
- ViewData["Test"] = test;
- return View();
- }
- }
Congratulations! You have successfully set up your Azure Redis Cache.