Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Daniel Ovaska
May 13, 2016
  2845
(0 votes)

Making a cache dependency on pagetype or ancestor

Based on a forum post question I wanted to take the new master key concept for caching out for a test drive.

Let’s say you want to cache stuff but directly a certain page type is updated anywhere you want to clear that cache. Might be a news listing or similar. Another common request is that you want to clear cache if anything is change below a certain root page. How do we make this using master keys?

Talking in code I want to do this (but with a CacheEvictionPolicy that works on both content types and a dependant root page):

var cacheKey = "KeyForItem";
var cachedItem = DateTime.Now.ToLongTimeString();
var cache = ServiceLocator.Current.GetInstance<ISynchronizedObjectInstanceCache>();
cache.Insert(cacheKey, cachedItem, cacheEviction);

To solve this I created two classes

1. A cache "manager" class that is responsible for creating some sweet cache invalidation policies and also to help invalidate cache. 2. An initialize module that subscribes to content events. This will basically just pass along any events to the cache manager and let that class determine if something needs to be invalidated.
public interface ICacheManager
{
   CacheEvictionPolicy GetCacheEvictionPolicy(TimeSpan duration, IEnumerable<Type> dependentTypes );
   CacheEvictionPolicy GetCacheEvictionPolicy(TimeSpan duration, IEnumerable<Type> dependentTypes, IEnumerable<ContentReference> roots);
   void OnContentChange(object sender, EPiServer.ContentEventArgs e);
}
//Class responsible for creating cache eviction policies and invalidate cache depending on content events...
public class CacheManager:ICacheManager
{
    private readonly ISynchronizedObjectInstanceCache _cache;
    private readonly IContentLoader _contentLoader;
    private readonly IContentTypeRepository _contentTypeRepository;
    public CacheManager(IContentTypeRepository contentTypeRepository,IContentLoader contentLoader, ISynchronizedObjectInstanceCache cache)
    {
            _contentTypeRepository = contentTypeRepository;
            _contentLoader = contentLoader;
            _cache = cache;
    }
    //Depending on page types...
    public CacheEvictionPolicy GetCacheEvictionPolicy(TimeSpan duration, IEnumerable<Type> dependentTypes )
    {
         return new CacheEvictionPolicy(null,null,dependentTypes.Select(t=> GetMasterKey(t)));
    }
    //Depending on ancestor node in content tree...
    public CacheEvictionPolicy GetCacheEvictionPolicy(TimeSpan duration, IEnumerable<Type> dependentTypes, IEnumerable<ContentReference> roots)
    {
        IEnumerable<string> dependentTypesKeys = new List<string>();
        if (dependentTypes != null)
        {
            dependentTypesKeys = dependentTypes.Select(t => GetMasterKey(t));
        }
        IEnumerable<string> ancestorKeys = new List<string>();
        if (ancestorKeys != null)
        {
             ancestorKeys = roots.Select(p => GetMasterKeyForAncestor(p));
        }
            return new CacheEvictionPolicy(null, null, dependentTypesKeys.Union(ancestorKeys));
     }

     private string GetMasterKeyForAncestor(ContentReference parent)
     {
        return $"Descendants:{parent.ID}";
     }
     private string GetMasterKey(Type type)
     {
           
            var contentType = _contentTypeRepository.Load(type);
            if (contentType != null)
            {
                return GenerateMasterKey(contentType);
            }
            return null;
     }

     private string GetMasterKey(IContent content)
     {
        var contentType = _contentTypeRepository.Load(content.ContentTypeID);
        return GenerateMasterKey(contentType);
     }

     private string GenerateMasterKey(ContentType type)
     {
        return $"ContentDependency:{type.GUID}";
     }
     //Invalidate cache if editor has changed a matching page...
     //Remember that a page can have children that is affected as well so need to take care of those as well
     public void OnContentChange(object sender, EPiServer.ContentEventArgs e)
     {
            var masterkey = GetMasterKey(e.Content);
            _cache.RemoveLocal(masterkey);
            var descendants = _contentLoader.GetDescendents(e.ContentLink);
            foreach (var contentLink in descendants)
            {
                var page = _contentLoader.Get<IContent>(contentLink);
                masterkey = GetMasterKey(page);
                _cache.RemoveLocal(masterkey);
            }
            masterkey = GetMasterKeyForAncestor(e.ContentLink);
            _cache.RemoveLocal(masterkey);
            var ancestors = _contentLoader.GetAncestors(e.ContentLink);
            foreach (var ancestor in ancestors)
            {
                masterkey = GetMasterKeyForAncestor(ancestor.ContentLink);
                _cache.RemoveLocal(masterkey);
            }
      }
}
//Set up some content events. 
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class PageEventsModule : IInitializableModule
{
        private static EPiServer.Logging.ILogger _log = LogManager.GetLogger(typeof(PageEventsModule));
        private ICacheManager _cacheManager;

        public void Initialize(InitializationEngine context)
        {
            // Configure the log4net.
            XmlConfigurator.Configure();
            _cacheManager = ServiceLocator.Current.GetInstance<ICacheManager>();
            var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>();
            contentEvents.PublishedContent += Instance_ContentChanged;
            contentEvents.MovedContent += Instance_ContentChanged;
            contentEvents.DeletedContent += Instance_ContentChanged;
            contentEvents.SavedContent += Instance_ContentChanged;
            contentEvents.MovingContent += Instance_ContentChanged;
        }
        

        void Instance_ContentChanged(object sender, ContentEventArgs e)
        {
            _cacheManager.OnContentChange(sender,e);
        }

        public void Uninitialize(InitializationEngine context)
        {
            var contentEvents = ServiceLocator.Current.GetInstance<IContentEvents>();
            contentEvents.PublishedContent -= Instance_ContentChanged;
            contentEvents.MovedContent -= Instance_ContentChanged;
            contentEvents.DeletedContent -= Instance_ContentChanged;
            contentEvents.SavedContent -= Instance_ContentChanged;
            contentEvents.MovingContent -= Instance_ContentChanged;
        }

        public void Preload(string[] parameters)
        {

        }
}

Now I can happily cache my items like this:

 var cacheEviction = cacheManager.GetCacheEvictionPolicy(new TimeSpan(0, 0, 10, 0),
                new[] { typeof(StandardPage) }, new[] {new ContentReference(6) });
 cache.Insert(cacheKey, cachedItem, cacheEviction);

...and if anything below the content node with id 6 is changed or any page of type "StandardPage" is changed, then the cache is invalidated.

The concept of master keys is really useful as you can see. It lets you clear parts of the cache easily and you can create powerful cache invalidation with ease.

Happy coding!

May 13, 2016

Comments

Please login to comment.
Latest blogs
Optimizely Configured Commerce and Spire CMS - Figuring out Handlers

I recently entered the world of Optimizely Configured Commerce and Spire CMS. Intriguing, interesting and challenging at the same time, especially...

Ritu Madan | Mar 12, 2025

Another console app for calling the Optimizely CMS REST API

Introducing a Spectre.Console.Cli app for exploring an Optimizely SaaS CMS instance and to source code control definitions.

Johan Kronberg | Mar 11, 2025 |

Extending UrlResolver to Generate Lowercase Links in Optimizely CMS 12

When working with Optimizely CMS 12, URL consistency is crucial for SEO and usability. By default, Optimizely does not enforce lowercase URLs, whic...

Santiago Morla | Mar 7, 2025 |

Optimizing Experiences with Optimizely: Custom Audience Criteria for Mobile Visitors

In today’s mobile-first world, delivering personalized experiences to visitors using mobile devices is crucial for maximizing engagement and...

Nenad Nicevski | Mar 5, 2025 |

Unable to view Optimizely Forms submissions when some values are too long

I discovered a form where the form submissions could not be viewed in the Optimizely UI, only downloaded. Learn how to fix the issue.

Tomas Hensrud Gulla | Mar 4, 2025 |

CMS 12 DXP Migrations - Time Zones

When it comes to migrating a project from CMS 11 and .NET Framework on the DXP to CMS 12 and .NET Core one thing you need to be aware of is the...

Scott Reed | Mar 4, 2025