My MVC application(SQL as database server) use Redis cache(Windows) inorder to improve performance and also to reduce the load on database server. Redis cache is hosted on separate VM(Single node) and stackexchange.redis is the client used to connect to Redis server.
I want to make my application resilient to redis cache server failure.
So, Incase of Redis server failure,instead of throwing error to user,application should still be able to fetch it from database.
Is there any fall back mechanism that i can use in my application code in case of Redis Cache server failure?
Thanks in Advance.
Below is my RedisCacheService class. I'm using DI container to inject IConnectionMultiplexer.
public class RedisCacheService :IRedisCacheService
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly IDatabase _redisCache;
public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
{
try
{
_connectionMultiplexer = connectionMultiplexer;
_connectionMultiplexer.ErrorMessage += _connectionMultiplexer_ErrorMessage;
_connectionMultiplexer.ConnectionFailed += _connectionMultiplexer_ConnectionFailed;
_connectionMultiplexer.ConnectionRestored += _connectionMultiplexer_ConnectionRestored;
_redisCache = _connectionMultiplexer.GetDatabase();
}
catch (Exception ex)
{
}
}
private void _connectionMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e)
{
//throw new NotImplementedException();
}
private void _connectionMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
//throw new NotImplementedException();
}
private void _connectionMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
//throw new NotImplementedException();
}
public T JsonGet<T>(RedisKey key, CommandFlags flags = CommandFlags.None)
{
RedisValue cacheData = _redisCache.StringGet(key, flags);
if (!cacheData.HasValue)
return default;
T rgv = JsonConvert.DeserializeObject<T>(cacheData);
return rgv;
}
public RedisValue GetCacheData(RedisKey key, CommandFlags flags = CommandFlags.None)
{
RedisValue cacheData = _redisCache.StringGet(key, flags);
if (!cacheData.HasValue)
return default;
//T rgv = JsonConvert.DeserializeObject<T>(cacheData);
return cacheData;
}
public bool SetCacheData(RedisKey key, object value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
{
if (value == null) return false;
return _redisCache.StringSet(key, JsonConvert.SerializeObject(value), expiry, when, flags);
}
}