Ehsan Ghanbari

Experience, DotNet, Solutions

Redis as a cache server

Although Redis is much more than a cache, But it's possible to use as cache server especially in distributed applications. Redis lets you operate on the values and it's just a key-value pair in-memory database.

To getting started, get the latest version of Redis from here and install in your windows machine (Server) by instruction and run it in your services. Redis runs in your server machine (you can have Redis server and client in one machine which could be your client development machine) and you call it from a client by a library. Now to work with Redis in a server you need to get stack exchange via Nuget and implement your methods provided by it.

Note: You can read all descriptions and instructions of stack exchange Redis in Github.

public class RedisCacheManager

    {

        private readonly ConnectionMultiplexer _connectionMultiplexer;

        private readonly IDatabase _dataBase;

        private IServer _server;



        private static Lazy<ConfigurationOptions> configurations = new Lazy<ConfigurationOptions>(() =>

        {

            var configuration = new ConfigurationOptions();

            configuration.EndPoints.Add("192.168.110.149:6421");

            configuration.ConnectTimeout = 100000;

            configuration.SyncTimeout = 100000;

            configuration.AllowAdmin = true;

            configuration.Password = "skdfenr4";

            return configuration;

        });



        public RedisCacheManager()

        {

            _connectionMultiplexer = ConnectionMultiplexer.Connect(configurations.Value);

            _dataBase = _connectionMultiplexer.GetDatabase();

            var endpoints = _connectionMultiplexer.GetEndPoints();

            _server = _connectionMultiplexer.GetServer(endpoints.First());

        }



        public object Retrieve(string key)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return rValue;

            return JsonHelper.Deserialize<object>(rValue);

        }



        public T Retrieve<T>(string key)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return JsonHelper.Deserialize<T>(null);

            return JsonHelper.Deserialize<T>(rValue);

        }



        public T Retrieve<T>(string key, int pageIndex)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return JsonHelper.Deserialize<T>(null);

            return JsonHelper.Deserialize<T>(rValue);

        }



        public bool Contain(string key)

        {

            return _dataBase.KeyExists(key);

        }



        public void Store(string key, object value)

        {

            if (value == null)

                return;



            var entryBytes = JsonHelper.Serialize(value);

            _dataBase.StringSet(key, entryBytes);

        }



        public void Store(string key, object value, int cacheTime)

        {

            if (value == null)

                return;



            var entryBytes = JsonHelper.Serialize(value);

            var expiresIn = TimeSpan.FromMinutes(cacheTime);



            _dataBase.StringSet(key, entryBytes, expiresIn);

        }



        public void Remove(string key)

        {

            _dataBase.KeyDelete(key);

        }



        public void Clear()

        {

            var endpoints = _connectionMultiplexer.GetEndPoints(true);

            foreach (var endpoint in endpoints)

            {

                var server = _connectionMultiplexer.GetServer(endpoint);

                server.FlushAllDatabases();

            }

        }



        private static byte[] Serialize(object item)

        {

            var jsonString = JsonConvert.SerializeObject(item);

            return Encoding.UTF8.GetBytes(jsonString);

        }



        private static T Deserialize<T>(byte[] serializedObjectValue)

        {

            if (serializedObjectValue == null)

                return default(T);



            var jsonString = Encoding.UTF8.GetString(serializedObjectValue);

            return JsonConvert.DeserializeObject<T>(jsonString);

        }

    }

 

I Just implemented the most used methods in a caching system, you can implement your own based on your needs. As you see I created configurations with some initializing. for example EndPoints(you can get it from the server that Redis is running on) and password (for making the connection between client and server secure).  In the constructor of the class, you need to connect to Redis server via ConnectionMultiplexer and get the database to work with.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC