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;
}
}
}