Example of how to use a CacheRefresher Notification
Before starting with cache refresher notifications it's a good idea to ensure you need to use them. If you want to react to changes in content, for instance, there's no real reason to use these notifications. This is due to the content service notifications being easier to work with. If you need to react to changes in the cache, then these are the notifications for you.
Cache refresher notifications are sent when the cache has refreshed. There are multiple different types of cache refresher notifications. These types are based on what type has been updated in the cache, for instance, content or media. All these notifications inherit from the same base notification: CacheRefresherNotification.
The base notification is implemented in the following way:
As you can see this notification contains two properties, a MessageObject and a MessageType. The MessageType specifies what kind of cache operation was performed, for example RemoveById. The possible message types is as follows:
The other parameter MessageObject will depend on what type of cache refresher notification you're handling. If you for instance handle the ContentCacheNotification, the message object will be ContentCacheRefresher.JsonPayload[].
This object contains the Id and key of the item being updated, as well as an enum specifying how the tree is updated:
[Flags]publicenumTreeChangeTypes:byte{ None =0, // all items have been refreshed RefreshAll =1, // an item node has been refreshed // with only local impact RefreshNode =2, // an item node has been refreshed // with branch impact RefreshBranch =4, // an item node has been removed // never to return Remove =8,}
An example of working with the ContentCacheNotification can be seen here:
usingUmbraco.Cms.Core.Cache;usingUmbraco.Cms.Core.Events;usingUmbraco.Cms.Core.Notifications;usingUmbraco.Cms.Core.Services;usingUmbraco.Cms.Core.Services.Changes;namespaceUmbraco.Cms.Web.UI;publicclassContentCacheRefresherExample:INotificationHandler<ContentCacheRefresherNotification>{privatereadonlyIContentService _contentService;publicContentCacheRefresherExample(IContentService contentService) { _contentService = contentService; }publicvoidHandle(ContentCacheRefresherNotification notification) {if (notification.MessageObjectisnotContentCacheRefresher.JsonPayload[] payloads) {return; }foreach (ContentCacheRefresher.JsonPayload payload in payloads) {if (payload.ChangeTypesisnotTreeChangeTypes.RefreshNodeorTreeChangeTypes.RefreshBranch) {return; } // You can do stuff with the ID of the refreshed content, for instance getting it from the content service.var refeshedContent =_contentService.GetById(payload.Id); } }}