Wednesday, June 5, 2013

Redis Hashes and ServiceStack

I am not a huge fan of extension and static methods, because they do not fit into OO design very well.  They are not objects, not extensible, override-able - just a dead end.  I also find that they are abused (not their fault) more often than not.  I have seen extension methods that call databases, chain together with several other extension and static methods creating a huge procedural mess.

For purposes of submitting code samples, they work great.  I can easily post a chunk of code that I want to discuss, and others can easily adopt it.

Anyway, one interesting feature of Redis' Hashes is that you can specify which values you want to retrieve.  Although it seems like a micro-optimization, it can really increase throughput and lower your network utilization.  An example of this optimization would be a hash that stores a photo, and exif information about the photo.  Often times you'll want just the exif, and not the actual image.

I was using the ServiceStack Redis client and discovered it has functionality that converts a .Net object into a Hash.  What it was lacking was a way to get a single property out of that hash, so I wrote a method in my repository to do that.  I extracted it into the extension method below:

I had to dig into the ServiceStack code to discover how it handles the creation of the key, and how it performs the json serialization.  One issue with this code is that it ignores the NamespacePrefix property.

Another interesting thing I learned about using their implementation is that they store all the keys of an entity in a Set.  So if you want to get a list of all your objects, you can do a SMEMBERS call to get the list of ids, then convert it to their key format and retrieve the objects.

I am not sure I like their implementation, but I need to learn more about it.

If you are interested in playing around with Redis and .Net, you can also use the Booksleeve client.