Caching Distributed Work Output in Redis with ASP.NET Core

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
namespace Samples.Redis
{
public class RedisWorkoutputCache : IWorkoutputCache
{
private ILogger logger;
private IConnectionMultiplexer connection;
public RedisWorkoutputCache(
ILogger<RedisLocationCache> logger,
IConnectionMultiplexer connectionMultiplexer)
{
this.logger = logger;
this.connection = connectionMultiplexer;
}
// DI Hack - shouldn't always need this
public RedisLocationCache(
ILogger<RedisWorkoutputCache> logger,
ConnectionMultiplexer connectionMultiplexer) : this(logger,
(IConnectionMultiplexer)connectionMultiplexer) {}
public IList<Workoutput> GetAllWorkoutput(Guid jobId)
{
IDatabase db = connection.GetDatabase();
RedisValue[] vals = db.HashValues(jobId.ToString());

return ConvertRedisValsToWorkputputList(vals);
}
public void Put(Guid jobId, Workoutput workOutput)
{
IDatabase db = connection.GetDatabase();

db.HashSet(jobId.ToString(),
workOutput.DispatchID.ToString(),
workOutput.ToJsonString());
}
private IList<MemberLocation>
ConvertRedisValsToWorkoutputList(RedisValue[] vals)
{
List<Workputput> workOutputs =
new List<Workoutput>();
for (int x=0; x<vals.Length; x++) {
string val = (string)vals[x];
Workoutput wo = Workoutput.FromJsonString(val);
workOutputs.Add(ml);
}
return workOutputs;
}
}
}
  • Create a Redis hash for every Job ID
  • Create a Redis field within the hash for each Dispatch/Work Item/Event ID
  • This field contains a JSON serialization of the work output
  • Use the HashValues method to get a list of all work items within a parent job.
{
"vcap:services" : {
"rediscloud" : [
{
"name" : "redislocationcache",
"label" : "rediscloud",
"plan" : "30mb",
"credentials": {
"port": "6379",
"hostname": "127.0.0.1",
"password": ""
}
}
]
}
<PackageReference 
Include="Steeltoe.Extensions.Configuration.CloudFoundry">
<Version>1.0.0-rc2</Version>
</PackageReference>
<PackageReference
Include="Steeltoe.CloudFoundry.Connector.Redis">
<Version>1.0.0-rc2</Version>
</PackageReference>
  • We can use a well-known Redis client in our ASP.NET Core apps (Stack Exchange)
  • We can use Steeltoe connectors in ASP.NET Core on Linux/Mac/Windows to pre-configure and instantiate a Redis client
  • We can use more advanced Redis concepts on the connection multiplexer like hashes in addition to the simple key-value pair pattern available on the distributed cache interface.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Hoffman

Kevin Hoffman

In relentless pursuit of elegant simplicity. Tinkerer, writer of tech, fantasy, and sci-fi. Converting napkin drawings into code for @CapitalOne