in General

Redis on Windows Azure

We’re rolling Redis caching into our project at work, so I though I’d give it a dummy run by first adding it into the Park Run site I made over the weekend. Is this overkill for such a simple site? Absolutely. The site works by screen scraping data from the official park run site. This is actually super-fast and there are no traffic considerations, so this is purely a learning exercise.

The Redis cache on Azure is brand new – right now it’s so new it’s only available via the Azure preview portal. Setup is simple, the only decisions I needed to make were the name, and to change the default location to Northern Europe (the same as the site). Once the cache is created you can access the HostName and Keys you’ll need to connect to the cache from your code.

The client I’ve used is StackExchange.Redis (at work we need running on Mono so we’re using a fork of ServiceStack called NServiceStack), which can be installed into your project with Nuget.

Once that’s set up you can connect to the cache, using the HostName and Key as the password:

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("parkrungraphs.redis.cache.windows.net,ssl=true,password=<VALUE_OF_KEY>");
var cache = connection.GetDatabase();</code>

This can be reused, it shouldn’t be created on a per-connection basis. The second line returns a reference to the database we can use to add and retrieve data. In the Park Run site, I’m using the cache as a simple key-value store. Any classes populated by data grabbed from the Park Run website get serialised and chucked into the cache. Happily Microsoft had made available a useful helper class to easily serialize my classes and add them to the cache using StringSet, so the code was as simple as this:

            var cache = GetRedisCache();
            var cachedRunnersData = (VenueData)cache.Get(venue);

            if (cachedRunnersData != null)
            {
                 return cachedRunnersData;
            }

            //Screen scraping code goes here.
            cache.Set(venue, venueData);
            return venueData;

Write a Comment

Comment