I have a CMS web application in ASP.NET Core 6 MVC. It has functionality to create content and publish to live website. Currently I'm using IMemoryCache as a caching mechanism and when I'm editing any content or doing some changes, I'm adding it to the cache. At the time of publish this cached content is not flushed out.
Now what I want is to track the content that is contained within a cached object, so that at publish time, we can smartly invalidate the cache of any object that references content that may have changed with a publish.
I have a simple way to do this: each time we write to cache, we should also write an object that describes the content inside.
Pseudo code example of this:
public class CacheContentIndex
{
// Start with this
List<int> ContentIDs;
// Examples of objects we could track in the future
List<int> ContentMenuIDs;
List<int> ContentMediaIDs;
}
Each time you make a call to CacheHelper.Add(), we should be passing in an extra parameter that takes an object of type CacheContentIndex(). As we’re going through a function, we should loop through the results, identify what these ID’s are, and then put them into that object.
When CacheHelper.Add() gets an object of type CacheContentIndex, under the hood, you should just save that to cache with a common prefix to the CacheKey that was passed in
Example: if the cache key passed in was MainMenu, you should make a cache save with the key CacheContentIndex_MainMenu.
At publish time, we'll need to:
- Identify each ID that gets touched as part of the publish (basically everything tracked in a
CacheContentIndexobject) - Make an outgoing web request to each publish endpoint to a common path where we POST an object that has all of those ID’s. Example path:
/cacheinvalidate - When requests come into that
/cacheinvalidatepath on the live websites, the following happens:
- Iterate through the values of all cache keys that start with
CacheContentIndex_. - In each, check to see if it has any content that matches what we are being told to invalidate.
Example: Say we have acachekeycalledMainMenu. Based on iterating all of the cache keys that start withCacheContentIndex_, we see that this content needs to be invalidated. So we expire two cache items:
MainMenuCacheContentIndex_MainMenu
But I want an alternate way to this method. I want to use CancellationTokenSource to invalidate caches, so I don't need to store CacheContentIndex in a different class.
Thanks in advance.