Overview
Hello Devs,
Hope you are aware of caching. Caching is a process of data stored into temporary storage so we can access this data more quickly when it is required. Redis cache is a Distributed caching so it can be accessed in multiple application servers. It improves performance and scalability because it can share the same data into multiple servers. If one server crashes then cache is still available on another server. You can use Redis cache in many programming languages, Microsoft Azure and Amazon Web Service (AWS) provide the use of Redis Cache with the name of Azure Cache and Amazon ElastiCache respectively. Let’s get some deep ideas about some features with their examples of Redis cache.
Introduction
Redis cache follows the concept of Distributed caching, so we can access this data in multiple servers with the Redis cache. It also allows us to access one server’s data into another server. In cache we store data that changes infrequently. So, we can access data directly from the cache when it’s required without calling the database. With Redis cache our application’s performance improves because it reduces database calls. It impacts the time consumed to call and service call efficiency.
Here are some features of the Redis cache.
- Open-source cache storage platform
- Distributed
- NoSQL key-value cache
- Store different data structures like string, hashes, lists, sets.
- Improves scalability and performance.
Connect Redis cache server in ASP.NET Core
To use Redis cache in the .NET, first we need to install a Redis cache server in the local machine or Microsoft Azure and AWS also provide us a server for Redis cache.
Create a new Console application. For Redis cache you need to install StackExchange.Redis NuGet package.
After installing the package we create a RedisConnectorHelper.cs file. This file is used to connect to the Redis cache server.
public class RedisConnectorHelper { static RedisConnectorHelper() { string redisConnectionString = "localhost:6379"; lazyConnection = new Lazy<ConnectionMultiplexer>(() => { return ConnectionMultiplexer.Connect(redisConnectionString); }); } private static Lazy<ConnectionMultiplexer> lazyConnection; public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } } }
ConnectionMultiplexer handles the connection and Connect() will return the connection’s instance.
Storing data into cache
In this section we see how we can insert data into cache.
StringSet() is the method that is used for storing string in the cache memory. It stores data in Key-Value pairs. If data exists with the same key then it overwrites old data.
public void SaveData() { int Id = 10000; var cache = RedisConnectorHelper.Connection.GetDatabase(); cache.StringSet("Id", Id); }
Retrieve data from the cache
StringGet() is the method that we can use for retrieving data from the cache. This Method takes one argument as the key and returns the value in the form of string. If the key does not exist on the server then it will not throw an error. It Just simply returns an empty string.
public void ReadData() { var cache = RedisConnectorHelper.Connection.GetDatabase(); if (!cache.KeyExists("Id")) { Console.WriteLine("Data Deleted"); return; } var value = cache.StringGet($"Id"); Console.WriteLine($"Id={value}"); }
Delete cache Data
The KeyDelete() method is used to delete data from the Redis cache server. This method also takes one argument that is Key. It deletes the key’s data and if the key does not exist then it does not throw any error.
Example:
public void DeleteCache() { var cache = RedisConnectorHelper.Connection.GetDatabase(); cache.KeyDelete("Id"); }
Other functions of Redis cache
The KeyExists() method is used to check whether the data in the key exists or not. This function will return true if the key exists otherwise it will return false.
Example:
if(cache.KeyExists("Id")) { //Code }
The KeyRename(key,newKey) method renames the key to newKey. It returns an error when the source and destination names are the same, or when the key does not exist.
Example:
cache.KeyRename("Id", "newId");
The KeyCopy(sourceKey,destinationKey) method copies the value from the Source keys to the specified destination key.
Example:
cache.StringSet("Id", "Id0001");//Id = Id0001 cache.KeyCopy("Id", "NewId"); //NewId = Id0001
The KeyExpire() method sets a timeout on key. Deletion of the key will be automatically done after the timeout has expired. If the key is updated before the timeout has expired, then the timeout is removed.
Example:
cache.KeyExpire("Id", TimeSpan.FromHours(1)); cache.KeyExpire("Name", DateTime.MaxValue);
The StringAppend() method appends the value at the end of the string if the key already exists. If the key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case.
Example:
cache.StringSet("Id", "S0001"); //S0001 cache.StringAppend("Id", "001"); //S0001001
The StringGetSet() method works for both Get value and Set value.This automatically sets key to value and returns the old value stored at key.
Example:
var oldvalue = cache.StringGetSet("Key", "newvalue");
Development ServicesGet Expert Assistance
Conclusion
Hope this blog helps you to understand and get a clear idea about caching and how to read, write and delete data from the Redis cache server.