• 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 NCache Web Manager.

Important

Cache level event notifications must be enabled from NCache Web 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 Web 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 Web 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 Web 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 Web 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 Web 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
// Create a target class
// Precondition: Events have been enabled through NCache Web Manager/ Config Files
public static void OnCacheDataModification(string key, CacheEventArg args)
{
    switch (args.EventType)
    {
        case EventType.ItemAdded:
            // 'key' has been added to the cache
            break;
        case EventType.ItemUpdated:
            // 'key' has been updated in the cache
            // Get the updated product
            if (args.Item != null)
            {
                Product updatedProduct = args.Item.GetValue<Product>();
                // Perform operations
            }
            break;
        case EventType.ItemRemoved:
            // 'key' has been removed from the cache
            break;
    }
}
// Create a target class
// Precondition: Events have been enabled through NCache Web 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")

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 an 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

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
try
{
    // Preconditions: Cache is already connected &
    // Events have been enabled through NCache Web Manager/Config Files

    // Register target method
    var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);

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

    // Register cache notifications with all three event types and sets the
    // EventDataFilter as DataWithMetadata which returns keys along with their entire data
    CacheEventDescriptor eventDescriptor = cache.RegisterCacheNotification(dataNotificationCallback,
    EventType.ItemAdded | EventType.ItemRemoved | EventType.ItemUpdated,
    EventDataFilter.DataWithMetadata);

    // Save the event descriptor for further usage
    // Perform your business logic
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
}
catch (Exception ex)
{
    // Any generic exception like ArgumentException, ArgumentNullException
}
try {
    // Precondition: Cache is already connected
    // Events have been enabled through NCache Web 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);
} catch (OperationFailedException exception) {
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception exception) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Precondition: Cache is already connected
    // Events have been enabled through NCache Web 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)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
try {
  // Preconditions: Cache is already connected &
  // Events have been enabled through NCache Web 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
  );
} catch (error) {
  // Handle errors
}
try:
    # Pre-conditions: Cache is already connected &
    # Events have been enabled through NCache Web 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)
except Exception as exp:
    # Handle errors

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 previously returned upon registering of event 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
try
{
    // Unregister Notifications using the EventDescriptor
    cache.MessagingService.UnRegisterCacheNotification(eventDescriptor);
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
}
catch (Exception ex)
{
    // Any generic exception like ArgumentException, ArgumentNullException
}
try {
    // Unregister Notifications using the EventDescriptor
    cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
} catch (OperationFailedException ex) {
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Unregister Notifications using the EventDescriptor
    cache.getMessagingService.removeCacheNotificationListener(eventDescriptor)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
try {
  // Unregister notifications using EventDescriptor
  await cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
} catch (error) {
  // Handle any errors
}
try:
    cache.get_messaging_service().remove_cache_notification_listener(event_descriptor)
except Exception as exp:
    # Handle errors
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