Insights

Clear The Sitecore CustomCache After Publishing

Part 3

The Problem

In our first article in the series, Part 1: How to Implement the Sitecore CustomCache that cached SOLR content search results. The problem with this cache is: how do we update the results when new items are added to the index?

Custom Cache Clearing On Publish

With our set up in Part 1, new items would not be available until the cache expires.

So lets implement a function that runs on the publish pipeline in Sitecore which clears our specified caches.


<sitecore>
	<events> 
		<event name="publish:end"> 
			<handler type="Namespace.CacheClearer, Mydll" method="ClearCaches"> 
				<caches hint="list"> 
					<cache>SearchResultsCache.SearchResults</cache> 
				</caches> 
			</handler> 
		</event> 
		<event name="publish:end:remote"> 
			<handler type="Namespace.CacheClearer, Mydll" method="ClearCaches"> 
				<caches hint="list"> 
					<cache>SearchResultsCache.SearchResults</cache> 
				</caches> 
			</handler> 
		</event> 
	</events>
</sitecore>

Here is the code that will clear out our custom cache(s) that we defined in the above XML


public class CacheClearer 
  {
    public void ClearCaches(object sender, EventArgs args)
    {
      Assert.ArgumentNotNull(sender, "sender");
      Assert.ArgumentNotNull(args, "args");
      try
      {
        DoClear();
      }
      catch (Exception ex)
      {
        Log.Error(this + ": " + ex, ex, this);
      }
    }
 
    private void DoClear()
    {
      foreach (string cacheName in Caches)
      {
        Cache cache = CacheManager.FindCacheByName(cacheName);
        if (cache == null)
          continue;
        Log.Info(this + ". Clearing " + cache.Count + " items from " + cacheName, this);
        cache.Clear();
      }
    }
 
    private readonly ArrayList _caches = new ArrayList();
    public ArrayList Caches
    {
      get
      {
        return this._caches;
      }
    }
  }

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting
 

Meet Mike Payne

Development Team Lead

🎶🚴‍♂️⛰

Mike is a Development Team Lead who is also Sitecore 9.0 Platform Associate Developer Certified. He's a BCIS graduate from Mount Royal University and has worked with Sitecore for over seven years. He's a passionate full-stack developer that helps drive solution decisions and assist his team. Mike is big into road cycling, playing guitar, working out, and snowboarding in the winter.

Connect with Mike