Introduction:
Redis stands for Remote Dictionary Server and is developed in C programming language. Redis is a fully managed, open-source, in-memory data store that enables high-performance and scalable architectures used by millions of developers as a database, cache, streaming engine, and message broker. Without cache, data is fetched from a relational database system in the following manner:
-
A user sends a request to the server
-
The server fetches data from the database
-
Database returns the data to the requested server
By using Redis Cache, we can optimize this system.
How does Azure Redis Cache improve application performance?
Azure Redis Cache handles data that needs to be accessed more frequently, while the database handles data that needs to be stored for the longer term.
Redis cache stores data in the form of key-value pairs in in-memory format. This means that Redis stores data in the primary memory (RAM), enabling very fast read and write speeds compared to relational databases that store data on SSDs or HDDs.
It is excellent for caching due to its high-speed read and write speeds which result from being stored on the primary memory(in-memory) itself. Redis has sub-millisecond response times and significantly reduces latency and load on your traditional RDBMS/NoSQL database.
What can we do using Azure Redis Cache?
1. Improve application performance
2. Speed up applications with a distributed cache
Benefits of Redis:
1. To avoid network calls
2. Avoid re-computations
3. Avoid load on the database
How network calls get reduced by using Redis Cache?
The client sends the request to the server. The server will check the value for the requested key in the cache; if it is present in the cache, the server will return that value. If it is not present, query data from the database and store that value in the cache in a key-value pair format. The server finally returns the value to the client from the cache.
If the client requests the same data (not changing frequently) again, the server will fetch data from the cache instead of the database. In this scenario, network calls will get reduced drastically.
Avoid re-computations:
Any computation that the server is often doing for a client request that won't change for a long time can be stored in the cache. So, the re-computation time done by the server will get reduced. This will also increase application performance.
Avoid load on the database:
For example, if you have a lot of servers and all hitting the database to get information, it will put a lot of loads on the database. Instead, servers will hit the cache instead of hitting the database if we cache that information in distributed Redis Cache. This will void the load on the database.
Redis server is the single-threaded process. A high Redis server load means that the server cannot keep pace with the requests from all the client connections. High memory usage indicates that your data size is too large for the current cache size. Consider scaling to a cache size with large memory and the appropriate service tier.
Service Tiers:
Azure Redis cache is available in these tiers.
Tier
|
Description
|
Basic
|
An OSS Redis cache running on a single VM. This tier has no service-level agreement (SLA) and is ideal for development/test and non-critical workloads.
|
Standard
|
An OSS Redis cache running on two VMs in a replicated configuration.
|
Premium
|
High-performance OSS Redis caches. This tier offers higher throughput, lower latency, better availability, and more features. Premium caches are deployed on more powerful VMs compared to the VMs for Basic or Standard caches.
|
Enterprise
|
High-performance caches powered by Redis Labs' Redis Enterprise software. This tier supports Redis modules, including RediSearch, RedisBloom, and RedisTimeSeries. Also, it offers even higher availability than the Premium tier.
|
Enterprise Flash
|
Cost-effective large caches powered by Redis Labs' Redis Enterprise software. This tier extends Redis data storage to non-volatile memory, cheaper than DRAM, on a VM. It reduces the overall per-GB memory cost.
|
Is Azure Redis Cache a database or cache?
Azure Redis Cache can be used as a standalone database. However, most of the time, it is best used to complement a database in the form of a cache.
Can Redis Cache replace RDBMS/NoSQL database?
Redis Cache cannot completely replace SQL Server. Microsoft SQL Server can be classified as a tool in the 'Databases' category, while Redis is grouped under 'In-Memory Databases'.
Redis is straightforward search capabilities, which means it is unsuitable for all use cases. Redis doesn't have good native support for storing data in object form. Many libraries are built over it and return data as a string, meaning you need to develop your serialization layer over it.
SQL Server is easy to understand and use. It is easy to export databases and tables in SQL queries or a script.
Let's see how to create Azure Redis Cache and use it in our application.
Create Azure Redis Cache:
Pre-requisite:
You’ll need an azure subscription before you begin.
1. To create cache, sign-in to the Azure portal and select ‘Create a resource’.
2. Select ‘Databases’ and then select ‘Azure Cache for Redis’.
3. On the New Redis Cache page, configure the settings for your new cache.
Setting
|
Choose a value
|
Description
|
Subscription
|
Drop down and select your subscription.
|
The subscription under which to create this new Azure Cache for Redis instance.
|
Resource group
|
Drop down and select a resource group or selectCreate newand enter a new resource group name.
|
Name the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
|
DNS name
|
Enter a unique name.
|
The cache name must be a string between 1 and 63 characters that contain only numbers, letters, or hyphens. The name must start and end with a number or letter and can't contain consecutive hyphens. Your cache instance'shost namewill be<DNS name>.redis.cache.windows.net.
|
Location
|
Drop down and select a location.
|
Select aregionnear other services that will use your cache.
|
Cache type
|
Drop down and select atier.
|
The tier determines the size, performance, and features that are available for the cache. For more information, seeAzure Cache for Redis Overview.
|
4. Select Networking tab and select your connectivity method.
5. In the Advanced tab, select the enable toggle if you want to enable a non-TLS port. You can select Redis version you would like to use, either 4 or 6.
6. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.
7. Select Review + Create. After validation passes, select Create.
It takes some time for the cache to create.
Now all are set to use Azure Redis Cache. Let’s create C# console application and see how Redis Cache is working. Below is the list of languages that Redis supports with the list of Redis clients (mentioned in the brackets).
- C (hiredis, hiredis-vip)
- C# (Redis, StackExchange.Redis)
- C++ (acl-redis)
- Java (Jedis, lettuce)
- Python (redis-py)
- js (ioredis, node_redis)
- PL/SQL (oredis)
- PHP (phpredis, Predis)
- Perl
- Swift (PSSRedisClient)
- Scala (scala-redis)
- Go (Radix)
How to use Azure Redis Cache in C#:
Create a console application in Visual Studio and then install the Redis client for .Net called StackExchange.Redis via the Nuget Packet Manager. You can also install this client in Nuget Packet Manager Console using the following command.
Install-Package StackExchange.Redis
To work with the StackExchange.Redis library, you should add the following statement in your program.
using StackExchange.Redis;
Establish a connection to Azure Redis:
To connect to an Azure Cache for Redis instance, cache client needs the access key for the cache. You can get the access keys from the Azure portal. To get access keys from your cache left navigation, select Access keys.
To connect to Azure Redis Cache, you need to use ConnectionMultiplexer class variable as a part of the StackExchange.Redis library. The important thing is you should share an instance of this class and reuse it throughout your application rather than create a connection instance for each operation.
1.private static ConnectionMultiplexer GetConnection()
2.{
3. String connectionString = "Azure-Redis-Demo.redis.cache.windows.net:6380,
4. password=YourRedisPassword=,ssl=True,abortConnect=False";
5. return ConnectionMultiplexer.Connect(connectionString);
6.}
Once the connection has been successfully established, you can use GetDatabase method of the ConnectionMultiplexer class to connect to the database inside Azure Redis Cache.
public static IDatabase Db => GetConnection().GetDatabase();
Store and retrieve objects from Azure Redis Cache:
You can store or retrieve objects to and from cache using the StringSet and StringGet methods respectively.
1. IDatabase redisCache = RedisCacheHelper.Db;
2.
3. redisCache.StringSet("Key1", "Test cache value");
4. string data = redisCache.StringGet("Key1");
5. Console.WriteLine(data);
Redis supports other data types also like Strings, Lists, Sets, Hashes, Sorted Sets, Bitmaps, and HyperLogLogs.
Output:
Conclusion:
Azure Redis Cache is available in three tiers—Basic, Standard, and Premium—with varied cache storage capacities and pricing. In the Basic and Standard tiers, data is stored in the memory of the virtual machine instance where the Redis service has been provisioned. If you want to persist the cached data to storage, then you will need to use the Premium tier. Only the Premium tier of Azure Redis Cache supports data persistence.
Even though Redis Cache cannot be used in place of a database, it serves as a great tool for caching mechanisms that drastically improve the application performance, thereby giving an excellent user experience.