2

We have this 90.000 lines Json object that takes 5 seconds to load. We need to load all this data since there is a lot of relations that needs to be included. Fortunately this data almost never change so it will basically always be the same (it do need to be able to snap out of the cache if the data updates)

Im not that good on server side cache so my question is.

  1. If i cache this serverside i guess all users will be served the cached answer until the cache releases?

  2. Can i cache this response on the server for until i somehow tell the api stop caching this? Its fine to hold 24 hours cache

  3. Any libriaries that i can achieve this with?

Regards

heathrow
  • 93
  • 8
  • you can also have a reference in this article. It has good examples https://michaelscodingspot.com/cache-implementations-in-csharp-net/ – dimmits Jan 03 '20 at 09:33

2 Answers2

3

You could use MemoryCache in .Net Framework

  1. MemoryCache lives in the Process, so all users can access the same cached data if you want (on the same server)
  2. You set the expiration time when saving to the cache.
  3. Built in the Framework
Daniel Stackenland
  • 3,149
  • 1
  • 19
  • 22
0

Thanks for the input my first attempt looks like this. It seems to work. Please provide feedback

        MemoryCache memoryCache = MemoryCache.Default;
        var test = memoryCache.Get("testKey")

        if (test != null) {
            return Ok(test) 
        } else {
            var data = GetData()
                 .ToList();

            memoryCache.Add("testKey", data, DateTimeOffset.UtcNow.AddDays(1));
            return Ok(data)
        }
heathrow
  • 93
  • 8
  • I've made a wrapper class around it ("CacheHelper") and I also use Constants for the the cacheKeys. I also use the Set method instead of Add, but as you use it It shouldn't make any difference, read more: https://stackoverflow.com/questions/8868486/whats-the-difference-between-memorycache-add-and-memorycache-set – Daniel Stackenland Jan 03 '20 at 09:23
  • Your code looks good. However, the cache returns items that are typed `object` so you may have to cast the item to the correct type. For example: `var test = memoryCache.Get("testKey") as YourType;` – mortb Jan 03 '20 at 10:54