• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

Cache Level Event Notifications

Note

This feature is only available in NCache Enterprise Edition.

Cache level notifications are fired when data is added, updated, or removed in cache from clients, Loader, and Backing Source, etc. By default, cache level events are disabled (except for cache cleared operation) and can be enabled through the NCache Manager.

Cache level event can be registered using RegisterCacheNotification by specifying the implemented callback, EventType, and EventFilter. Here, we describe how you can register and unregister cache level events.

Note

The application will not be able to receive events unless it registers itself against cache using the specific event registration API call.

Prerequisites

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • Make sure to enable event notifications using NCache Manager.
  • For API details, refer to: ICache, RegisterCacheNotification, EventType, EventDataFilter, UnRegisterCacheNotification, CacheEventDescriptor, CacheDataNotificationCallback.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • Make sure to enable event notifications using NCache Manager.
  • For API details, refer to: Cache, CacheDataModificationListener, CacheEventDescriptor, removeCacheNotificationListener, addCacheNotificationListener, EventType, EventDataFilter.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • Make sure to enable event notifications using NCache Manager.
  • For API details, refer to: Cache, CacheEventDescriptor, CacheDataModificationListener, getEventType, CacheEventArg.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • Make sure to enable event notifications using NCache Manager.
  • For API details, refer to: Cache, CacheDataModificationListener, getEventType, removeCacheDataNotificationListener,getMessagingService, addCacheDataNotificationListener, EventType, getMessagingService, addCacheNotificationListener.
  • To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
  • Make sure to enable event notifications using NCache Manager.
  • For API details, refer to: Cache, EventType, EventDataFilter, CacheEventDescriptor, get_messaging_service, CacheEventArg, add_cache_notification_listener, get_event_type, remove_cache_notification_listener.

Implement Callback for Event Notifications

You can implement a callback for events where EventType is specified according to the user's logic for ItemAdded, ItemUpdated and ItemRemoved events.

The following example implements a callback method for cache notifications with certain event types.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
public void OnCacheDataModification(string key, CacheEventArg args)
{
    switch (args.EventType)
    {
        case EventType.ItemAdded:
            Console.WriteLine($"Item with Key '{key}' has been added to cache '{args.CacheName}'");
            break;

        case EventType.ItemUpdated:
            Console.WriteLine($"Item with Key '{key}' has been updated in the cache '{args.CacheName}'");

            // Item can be used if EventDataFilter is DataWithMetadata or Metadata
            if (args.Item != null)
            {
                Product updatedProduct = args.Item.GetValue<Product>();
                Console.WriteLine($"Updated Item is a Product having name '{updatedProduct.ProductName}', price '{updatedProduct.UnitPrice}', and quantity '{updatedProduct.QuantityPerUnit}'");
            }
            break;

        case EventType.ItemRemoved:
            Console.WriteLine($"Item with Key '{key}' has been removed from the cache '{args.CacheName}'");
            break;
    }
}
// Create a target class
// Precondition: Events have been enabled through NCache Manager/ Config Files
// Create a class implementing CacheDataModificationListener interface
public class EventListener implements CacheDataModificationListener {
    @Override
    public void onCacheDataModified(String s, CacheEventArg cacheEventArg) {
        // write code here
    }
    @Override
    public void onCacheCleared(String s) {
        // write code here
    }
}
class DataModificationListener extends CacheDataModificationListener {
  override def onCacheDataModified(key: String, eventArgs: CacheEventArg): Unit = {
    eventArgs.getEventType match {
      case EventType.ItemAdded =>
      // Key has been added to the cache

      case EventType.ItemUpdated =>
        // 'key' has been updated in the cache
        // get the updated product
        if (eventArgs.getItem != null) {
          val updateProduct = eventArgs.getItem.getValue(classOf[Product])
          // perform operations
        }

      case EventType.ItemRemoved =>
      // 'key' has been removed from the cache

    }
  }
override def onCacheCleared(cacheName: String): Unit = {
    print("Cache cleared.")
  }
}
// Create a target class
// Precondition: Events have been enabled
async onCacheDataModified(key, arg) {
    if (null != arg.getEventType()) {
        switch (arg.getEventType()) {
            // perform operations
        case ncache.EventType.ItemAdded:
            // key has been added to cache
            break;
        case ncache.EventType.ItemUpdated:
            // key has been updated in cache
            break;
        case ncache.EventType.ItemRemoved:
            // key has been removed from cache
            break;
        default:
            break;
        }
    }
}
def on_cache_data_modified(key: str, arg: ncache.CacheEventArg):
    if arg.get_event_type() is not None:
        if arg.get_event_type() is ncache.EventType.ITEM_ADDED:
            # Key has been added to cache
            print("Item added")
        elif arg.get_event_type() is ncache.EventType.ITEM_UPDATED:
            # Key has been updated in cache
            print("Item updated")
        elif arg.get_event_type() is ncache.EventType.ITEM_REMOVED:
            # key has been removed from cache
            print("Item removed")
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Register Cache Notifications

To register cache level notifications, a target method is created which can have multiple callbacks. The method contains an Event Type and Event Filter. The EventType is adjusted according to the type of operation whose notifications the user wants. The EventDataFilter can have one of the three possible values: None, MetaData, DataWithMetadata. The events will be notified to their appropriate listeners and handled as implemented by the user.

Important

The EventDataFilter must be carefully set to avoid unnecessary network bandwidth consumption.

The following example creates a method that registers callbacks for cache notifications with certain event types.

Note

If EventDataFilter is not specified, EventDataFilter.None is set automatically.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
public void RegisterCacheNotificationsForAllOperations()
{
    // create CacheDataNotificationCallback object
    var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);

    // Register cache notification with "ItemAdded" EventType and 
    // EventDataFilter "None" which means only keys will be returned
    CacheEventDescriptor eventDescriptor = cache.MessagingService.RegisterCacheNotification(dataNotificationCallback, EventType.ItemAdded | EventType.ItemUpdated | EventType.ItemRemoved, EventDataFilter.None);

    if (eventDescriptor.IsRegistered)
    {
        Console.WriteLine("Cache level notifications registered successfully");
    }
}
// Events have been enabled through NCache Manager/Config Files

// Create event listener instance of above implemented class and enum set of event type ItemAdded
var eventListener = new EventListener();
EnumSet<com.alachisoft.ncache.runtime.events.EventType> enumSet = EnumSet.of(EventType.ItemAdded);

// Register cache notification with "ItemAdded" EventType and "None"
// EventDataFilter which means only keys will be returned
cache.getMessagingService().addCacheNotificationListener(eventListener, enumSet, EventDataFilter.None);

// Register cache notifications and set the
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
CacheEventDescriptor data = cache.getMessagingService().addCacheNotificationListener(eventListener.onCacheDataModified(key2, arg2), enumSet, EventDataFilter.DataWithMetadata);
// Events have been enabled through NCache Manager/Config Files

// Create event listener and enum set of event type ItemAdded
val eventListener = ItemLevelDataModificationListener()
val eventTypes = List(EventType.ItemAdded)

// Register cache notification with "ItemAdded" EventType and "None"
// EventDataFilter which means only keys will be returned
cache.getMessagingService.addCacheNotificationListener(eventListener, eventTypes, EventDataFilter.None)

// Register cache notifications and set the
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
val data = cache.getMessagingService.addCacheNotificationListener(eventListener, eventTypes, EventDataFilter.DataWithMetadata)
// Events have been enabled through NCache Manager/Config Files

// Register cache notification with "ItemAdded" EventType and "None"
// EventDataFilter which means only keys will be returned
let eventListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);

let messagingService = await this.cache.getMessagingService();
await messagingService.addCacheNotificationListener(
eventListener,
ncache.EventType.ItemAdded,
ncache.EventDataFilter.None
);

// Register cache notifications and set the
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
let EventListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);

let messagingService2 = await this.cache.getMessagingService();
let data = await messagingService2.addCacheNotificationListener(
eventListener,
ncache.EventType.ItemAdded,
ncache.EventDataFilter.DataWithMetadata
);
# Events have been enabled through NCache Manager/Config Files

# Register cache notification with "ItemAdded" EventType and "None" 
# EventDataFilter which means only keys will be returned

messaging_service = cache.get_messaging_service()
messaging_service.add_cache_notification_listener(event_listener, [ncache.EventType.ITEM_ADDED], ncache.EventDataFilter.NONE)

# Register cache notifications and set the 
# EventDataFilter as DataWithMetadata which returns keys along with their entire data  
messaging_service_2 = cache.get_messaging_service()
messaging_service_2.add_cache_notification_listener(event_listener, [ncache.EventType.ITEM_ADDED], ncache.EventDataFilter.DATA_WITH_META_DATA)

Unregister Cache Level Events

A previously registered Cache Level Notification can also be unregistered if it is no longer required using the UnRegisterCacheNotification method. Using this method, the CacheEventDescriptor also needs to be specified to unregister the notifications. For Java and Node.js, removeCacheDataModificationListener is used to unregister the event notifications.

The following example shows how to unregister notifications using this method.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
// Unregister Notifications using the EventDescriptor
cache.MessagingService.UnRegisterCacheNotification(eventDescriptor);
// Unregister Notifications using the EventDescriptor
cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
// Unregister Notifications using the EventDescriptor
cache.getMessagingService.removeCacheNotificationListener(eventDescriptor)
// Unregister notifications using EventDescriptor
await cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
// Unregister notifications using EventDescriptor
cache.get_messaging_service().remove_cache_notification_listener(event_descriptor)
Note

Using Cache Level Events might affect the performance of your application, since it fires notifications for all specified operations performed on the entire cache data set. Item Level Events is the recommended approach to avoid this problem.

Additional Resources

NCache provides a sample application for Cache Level Event Notifications on GitHub.

See Also

Item Level Event Notifications
Pub/Sub Messaging
Search Cache with LINQ

Back to top Copyright © 2017 Alachisoft