Thursday, May 30, 2019

REDIS Cache with C#, Learning Redis Cache, Capture DataTable into Redis Server

Redis Cache is a key-value cache that stores the information in a hash table format, providing the possibilities to store different types of structured data like strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs

1. Install Redis server (redis-server.exe) on your machine

2. Create RedisConnectorHelper class file

    public class RedisConnectorHelper
    {
        static RedisConnectorHelper()
        {
            RedisConnectorHelper.lazyConnection = new Lazy(() =>
            {
                return ConnectionMultiplexer.Connect("localhost");
            });
        }

        private static Lazy lazyConnection;

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
    }


3. You will noticed here ConnectionMultiplexer is not found in your application, so add using NuGet Package manager, search "StackExchange.Redis"

4. After installation you are ready to work in Redis application

5. Create the connection object of Redis server like this
    var cache = RedisConnectorHelper.Connection.GetDatabase();

6.  Store your values in this way
     cache.StringSet($"Device_Status:{i}", "value");

7. Retrive Redis/Cached values this way
     var value = cache.StringGet($"Device_Status:{i}");

8.  Some time we need to store DataTable into session/cache object so same we can do in following way.

    Store Values in Redis server:
   
   string TableName = "GetEmpData";
   foreach (DataRow dr in GetEmpData().Rows)
   {
      cache.StringSet($"Device_Status:"+ TableName + "_" +dr["id"].ToString(), string.Format("{0} : {1} : {2} : {3}", dr["Id"].ToString(), dr["Name"].ToString(), dr["Mobile"].ToString(), dr["Date"].ToString()));
   }

    Retrive Values from Redis server:
 
  foreach (DataRow dr in GetEmpData().Rows)
   {
     var value = cache.StringGet($"Device_Status:" + TableName + "_" + dr["id"].ToString());
     Console.WriteLine($"New Valueeeeee={value}");
   }
 
9. Sample Code Download Here

10. For Details information you can also visit the below link,

https://www.c-sharpcorner.com/UploadFile/2cc834/using-redis-cache-with-C-Sharp/

No comments:

Post a Comment