Monday, 22 May 2017

Clearing application cache on Sitecore publish

This blog post will talk about a general problem which we face or may have faced while implementing Sitecore solutions where we have used any custom or application level caching.

One most common example where we face this issue is while setting our sublayout/rendering as cacheable in code.


The above screenshot has a property "Cacheable=True", which caches the "Test.ascx" sublayout.
The above caching is maintained even after we publish the sublayout or even the whole site.

Issue: The content author reviews and updates the content for the Test.ascx and saves it, then publishes it. Now, he visits the website to see how the changes look, but to his surprise the page is still rendering the old content. This causes the developer to step in and after some dew diligence he see the content is updating in the web DB, but still not appearing on the screen, since it is cached.

Solution: As, the content is cached at application level, clearing Sitecore cache will not help. (Moreover, it has already been cleared on Publish by the Author). So, we can have 2 ways in which we can overcome this issue:
  • Recycle the app pool for the website (which is not a viable solution as the website restarts & Manual)
  • Or, inject something in the publish end event which clears the application cache every time content author make changes and publish those changes.

Firstly, below is the default handler provided by Sitecore at publish end & publish end remote event:

Which when decompiled will give us the logic just to clear the Sitecore Html cache using Sitecore's "CacheManger":

The above code does half of the job, but for the rest half we need to actually write our own logic at the same place i.e at the end of publish to clear the application cache.

Steps to add a custom event to clear the cache at publish end:
1) Add a new class to solution and add the code mentioned below:

The above logic will clear the cache and also log info in your log file when it will do so.

2) Now we have to inject this logic at the end of publish, so we will create a patch config and add the above class info there: 

Here, we can see that the new handler we created is patched at 2 places: "publish:end" and "publish:end:remote". The publish end remote handler will be used in the case where our CD(Content delivery) which is using the web database is on a remote server and needs to clear its cache on publish.
We should ensure the above should be patched at both places as the production CM and CD are hosted mostly on a separate server.

No comments:

Post a Comment