Sending and Retrieving Data From Redis Cache

Recently while working on LAMBDA's for Amazon Web Services (AWS) we needed to cache data using Redis and ElastiCache. One of the older projects was already using the StackExchange.Redis NuGet package for the .NET Framework, so I used the same for the LAMDA's. Unfortunately, I ran into many issues with StackExchange that included connection and timeout problems. While researching these issues it seemed I wasn't the only one and others said that StackExchange were very slow fixing them.

This worried me and I couldn't spend too much time trying to figure out the issues, so I switched to using the ServiceStack.Redis NuGet package. After switching the issues I was seeing connecting to Redis went away. It's also a lot easier to use!

Here is some example code to store and retrieve data using ServiceStack.Redis.

/// <summary>
/// Stores data into Redis cache.
/// </summary>
/// <param name="host">The redis host name.</param>
/// <param name="key">The key.</param>
/// <param name="data">The data.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public static bool Cache(string host, string key, string data)
{
Encapsulation.TryValidateParam(host, nameof(host));
Encapsulation.TryValidateParam(key, nameof(key));
Encapsulation.TryValidateParam(data, nameof(data));

using (var manager = new RedisManagerPool(host.Trim()))
{
using (var cache = manager.GetClient())
{
return cache.Set(key.Trim(), data);
}
}
}
/// <summary>
/// Loads data from Redis cache.
/// </summary>
/// <param name="host">The Redis host name.</param>
/// <param name="key">The key.</param>
/// <returns>System.String.</returns>
public static string Load(string host, string key)
{
Encapsulation.TryValidateParam(host, nameof(host));
Encapsulation.TryValidateParam(key, nameof(key));

using (var manager = new RedisManagerPool(host.Trim()))
{
using (var redisClient = manager.GetClient())
{
var messageBody = redisClient.Get<string>(key.Trim());
return messageBody;
}
}
}

In the code above, the calls to Encapsulation.TryValidateParam is from the dotNetTips.Utility.Standard NuGet package.

McCarter Consulting
Software architecture, code & app performance, code quality, Microsoft .NET & mentoring. Available!