Wednesday, June 27, 2018

Redis Cache


1.    What is Redis Cache?

Caching is a state management strategy that can be used to improve the performance of your applications as it helps you to reduce the consumption of resources in your system.

Redis Cache is an open source (BSD licensed), high-speed, NoSQL database. It's fast, and it runs entirely in the memory with negligible performance overhead when reading and writing data. It should be noted that Redis is free for both commercial and non-commercial use under the BSD license.

2. Install and proceed with Redis Cache implementation


Once the Redis database setup is done, we need Redis client to store and retrieve the data to and from the Redis cache.

Step 1>

1.     Install StackExchange.Redis package from nugget package.


Once the StackExchange.Redis installation is done. Please follow the below steps to store and retrieve data to and from the Redis cache.

Step2 >

2.     Open connection to Redis Cache


  Var RedisConnectionString=connection string
 if(RedisConnection.IsConnected)
   {
      Var ServerCache = RedisConnection.GetServer(RedisConnectionString);
      Var DBCache = RedisConnection.GetDatabase();
            HttpContext.Current.Application["RedisDB"] = DBCache;
    }

Step3 >

3.     Set the data in the Redis

Var _database= System.Web.HttpContext.Current.Application["RedisDB "];
   if(_database != null && _database.IsConnected(key))
      {
        ISerializer _serializer = new JsonSerializer();
        _database.StringSet(key, _serializer.Serialize(value), RedisExpireIn);

       }



Step4 >

4.     Get the data from Redis Cache

Var _database= System.Web.HttpContext.Current.Application["RedisDB "];
ISerializer _serializer = new JsonSerializer();
                if (_database != null && _database.IsConnected(key))
                {
                    _serializer.Deserialize<T>(_database.StringGet(key));
                }
               
       

5.     Delete key from Redis Cache


if (_database != null && _database.IsConnected(key))
                {
                   _database.KeyDelete(key);
                }

6.     Extending the Cache key Expiry


Var _database= System.Web.HttpContext.Current.Application["RedisDB "];
_database.KeyExpire(key, RedisExpireIn);

3. Reference


No comments:

Post a Comment