Using Azure Redis Cache On Your .NET Core Application - Part Two

In 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. 
To understand how to set up your Azure Redis Cache Database and more about its usage, check it here.
 
In this approach, we are going to use StackExchange.Redis to connect with the Azure Redis Database and BinaryFormatter to serialize and deserialize the data. No NuGet packages are required since Azure Redis Cache Database is already there inside .NET Core package.

How to do it?

Follow the next steps.

Complex Object Sample 

This is the complex object used in this sample.
  1. [Serializable]  
  2. public class SampleObject  
  3. {  
  4.     public int Id { getset; }  
  5.     public string Name { getset; }  
  6.     public string Country { getset; }  
  7. }  
PS.: As we must serialize the data in order to send or receive from Azure Redis Cache, this [Serializable] tag is a must.

Configure your Azure Redis Database connection

This method is going to return our Azure Redis database:
  1. public static IDatabase GetDatabase()  
  2.      {  
  3.          IDatabase databaseReturn = null;  
  4.          string connectionString = "TVtesting.redis.cache.windows.net:6380,password=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,ssl=True,abortConnect=False";  
  5.          var connectionMultiplexer = ConnectionMultiplexer.Connect( connectionString );  
  6.          if ( connectionMultiplexer.IsConnected )  
  7.              databaseReturn = connectionMultiplexer.GetDatabase();  
  8.   
  9.          return databaseReturn;  
  10.      }  
How to get your Azure Redis connection string? Check it here.

Set up your class to serialize and deserialize data based on BinaryFormatter 
 
Here we have the class that is used to serialize/deserialize the data and to connect to the database, as well as the database configuration method:
  1. public static class RedisCacheHelper  
  2.    {  
  3.        public static T Get<T>( string cacheKey )  
  4.        {  
  5.            return Deserialize<T>( GetDatabase().StringGet( cacheKey ) );  
  6.        }  
  7.   
  8.        public static object Get( string cacheKey )  
  9.        {  
  10.            return Deserialize<object>( GetDatabase().StringGet( cacheKey ) );  
  11.        }  
  12.   
  13.        public static void Set( string cacheKey, object cacheValue )  
  14.        {  
  15.            GetDatabase().StringSet( cacheKey, Serialize( cacheValue ) );  
  16.        }  
  17.   
  18.        private static byte[] Serialize( object obj )  
  19.        {  
  20.            if ( obj == null )  
  21.            {  
  22.                return null;  
  23.            }  
  24.            BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
  25.            using ( MemoryStream objMemoryStream = new MemoryStream() )  
  26.            {  
  27.                objBinaryFormatter.Serialize( objMemoryStream, obj );  
  28.                byte[] objDataAsByte = objMemoryStream.ToArray();  
  29.                return objDataAsByte;  
  30.            }  
  31.        }  
  32.   
  33.        private static T Deserialize<T>( byte[] bytes )  
  34.        {  
  35.            BinaryFormatter objBinaryFormatter = new BinaryFormatter();  
  36.            if ( bytes == null )  
  37.                return default( T );  
  38.   
  39.            using ( MemoryStream objMemoryStream = new MemoryStream( bytes ) )  
  40.            {  
  41.                T result = (T)objBinaryFormatter.Deserialize( objMemoryStream );  
  42.                return result;  
  43.            }  
  44.        }  
  45.   
  46.        public static IDatabase GetDatabase()  
  47.        {  
  48.            IDatabase databaseReturn = null;  
  49.            string connectionString = "TVtesting.redis.cache.windows.net:6380,password=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,ssl=True,abortConnect=False";  
  50.            var connectionMultiplexer = ConnectionMultiplexer.Connect( connectionString );  
  51.            if ( connectionMultiplexer.IsConnected )  
  52.                databaseReturn = connectionMultiplexer.GetDatabase();  
  53.   
  54.            return databaseReturn;  
  55.        }  
  56.    }  
Save complex object
  1. SampleObject sampleObject = new SampleObject  
  2. {  
  3.     Country = "Brazil",  
  4.     Id = 7,  
  5.     Name = "Mané"  
  6. };  
  7. RedisCacheHelper.Set( "test1", sampleObject );  

Get complex object

  1. var  sampleObject = RedisCacheHelper.Get<SampleObject>( "test1" );  

Save a list of complex object

  1. List<SampleObject> lstSampleObject = new List<SampleObject>();  
  2.             if ( RedisCacheHelper.GetDatabase() != null )  
  3.             {  
  4.                 lstSampleObject.Add( new SampleObject  
  5.                 {  
  6.                     Country = "Argentina",  
  7.                     Id = 1,  
  8.                     Name = "Maradona"  
  9.                 } );  
  10.                 lstSampleObject.Add( new SampleObject  
  11.                 {  
  12.                     Country = "Portugal",  
  13.                     Id = 2,  
  14.                     Name = "Ronaldo"  
  15.                 } );  
  16.                 lstSampleObject.Add( new SampleObject  
  17.                 {  
  18.                     Country = "Puskas",  
  19.                     Id = 3,  
  20.                     Name = "Hungary"  
  21.                 } );  
  22.                 RedisCacheHelper.Set( "test2", lstSampleObject );  
  23.             }  

Get a list of complex object 

  1. var lstSampleObject = RedisCacheHelper.Get<List<SampleObject>>( "test2" );  
Congratulations! You have successfully set up your Azure Redis Cache with complex objects. 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now