Beware base.RequestContext.ToOptimizedResultUsingCache

Standard

Loving learning Servicestack, it’s a fantastic framework.  I’ve come across a gotcha this morning (and last night (and the day before!)).

The caching is really simple and can backend onto Memcached, Redis amongst others.  This is where my story starts; On the dev boxes the app caches to memached, but the production servers use Redis.  There is a subtle difference in how objects are serialised for storig in memcached versus Redis – the Redis Cache client uses a serialisation to string.

This doesn’t work for complex objects, to make complex objects work with Redis then the RedisNativeClient needs to be used.  This is fine, once you realise what is happening and our system as a RedisNativeClient available for when it is needed.

Where I got caught out was the pattern for caching web requests is (from here):

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        return base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=> 
            {
                //Delegate is executed if item doesn't exist in cache 
                //Any response DTO returned here will be cached automatically
            });
    }
}

The bit that caught me out was the link to the requestcontext seems to control how the request is serialised rather than the response.

The work around is just to use the cache manually.

Advertisements