Skip to content

Instantly share code, notes, and snippets.

@timgabrhel
Created March 12, 2016 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timgabrhel/8a5ae727bacd87c2d5a9 to your computer and use it in GitHub Desktop.
Save timgabrhel/8a5ae727bacd87c2d5a9 to your computer and use it in GitHub Desktop.
Mini Redis Cache Transient Exception Handling
/// <summary>
/// A simple implementation to automatically retry transient connection error's to cache. Runs for a maximum of 10 seconds before timing out.
/// </summary>
protected TResult AttemptCacheCall<TResult>(Func<TResult> codeFunc)
{
var timeout = false;
var timer = new Timer(10000);
timer.Elapsed += (sender, args) => timeout = true;
timer.AutoReset = false;
timer.Start();
while (true)
{
if (timeout) { throw new TimeoutException("Unable to communicate with the cache instance in the timeout provided.");}
try
{
return codeFunc();
}
catch (Exception ex)
{
// Non-transient exception encountered
if (IsTransient(ex) == false)
{
throw;
}
// Transient cache call encountered.
// The while loop will continue & try the call again
}
}
}
/// <summary>
/// Looks at the returned exception and determines if the type is one that infers a transient based exception.
/// </summary>
public bool IsTransient(Exception ex)
{
if (ex == null) return false;
if (ex is TimeoutException) return true;
if (ex is RedisServerException) return true;
if (ex is RedisException) return true;
if (ex.InnerException != null)
{
return IsTransient(ex.InnerException);
}
return false;
}
/// <summary>
/// A simple usage example that wraps a call inside a transient retry handler.
/// </summary>
private bool KeyExists(string key)
{
return AttemptCacheCall(delegate
{
// Cache.StringGet is a call on the Redis .NET SDK IDatabase instance.
// See Azure Redis documentation for further usage.
var obj = Cache.StringGet(key);
return (obj != RedisValue.EmptyString && obj != RedisValue.Null);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment