mariocatch
mariocatch

Reputation: 8703

ServiceStack: How to tell if a return from a request was cached?

I have the caching hooked up in my request, but I'd like to be able to tell if the return I'm getting back is actually coming from the cache or not. Is there a way to see this? I have access to the code-base to make modifications.

ServiceStack's standard caching pattern:

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
            });
    }
}

Upvotes: 2

Views: 291

Answers (1)

Mike
Mike

Reputation: 1837

As mentioned in your comments the delegate passed to the ToOptimizedResultUsingCache method is only executed if the item doesn't exist in the cache. I would just add a "cached at" property to the response DTO and set it in that delegate.

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
            return new MyReturnDto {
                CachedAt = DateTime.Now
            };                
        });
    }
}

You can then use the CachedAt property to see when the item was cached.

If you don't want to modify your DTO you can just use a variable outside of the scope of delegate called when caching the result.

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        var isCached = false;
        var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
            isCached = true;             
        });
        // Do something if it was cached...
    }
}

Upvotes: 3

Related Questions