Repopulate the cache

Let me explain my case. Let’s say we have a widget on a page and the user request the last 4 hours of data. I then have a request with a relative time range of Now -4 hours. At the first request, we get the data and cache it with, let’s say a key of *-4h and we give back the orignal absolute start and end time of the request.

10 minutes later, the user clicks refresh which will still be Now-4 hours. I would get the same key but I would expect different results. What I would like to do is to retrieve the data I have from cache, truncate the first 10 minutes and only get the 10 minutes missing from the datasource. I would then have to recache the result.

Before I go and explore this, can you tell me if this is something feasible? I know I could probably get the cached data and recreate it but how to cache it again if what I am doing is not inside the delegate of the ToOptimizedResultUsingCache?

Thanks for your help.

I can’t quite follow all the varying app caching requirements but I’d forget about ToOptimizedResultUsingCache() which creates multiple caches on different serialized formats (inc compressed) that can vary per request and just cache the data in the local memory cache which you can retrieve from anywhere with:

var memoryCache = HostContext.AppHost.GetMemoryCacheClient();

Or use MemoryCacheClient in your dependencies if you want it injected by the IOC.

Then treat the cache like a transient Hash. You’re going to want to store enough information in your cached entry to be able to determine the range of cached data so you can easily determine what’s required to fetch the most up to date info. If you want to then piece together and resave that information you’ll need to use GetTimeToLive() (which Memory CacheClient supports) to workout how much time is remaining when you resave it.

Although I’d personally avoid resaving it just have an 1hr expiry and do a new query when it expires, that way there cache is only populated with the same query (i.e. instead of manual piecing), but I don’t know how relevant that approach is for your use-case.

1 Like

Thank you very much for the quick reply. You give me another reason to love using ServiceStack!
That will do the trick.

1 Like