• 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 Events are general events for cache which are triggered upon the execution of the registered activities/event types. The user can register Cache Level Events for any change in the cache data set, i.e add, update, or remove.

By default, Cache Level Events are disabled (except for cache cleared operation) for any cache configuration and must be enabled for events to be published using NCache Web Manager. Cache level notifications are fired when data is added, updated or removed in cache from clients, loader, read-through, etc.

Cache level data notifications can be used to share data across different clients. The purpose of this feature is to notify clients about every operation performed on cache. Following are the notifications fired when certain cache-level events are triggered:

  • Add Notification: Add notification is triggered when a new item is added to the cache. All applications which have registered this event will receive a notification when data is added to the cache.

  • Update Notification: Update notification is triggered when an existing item is updated in the cache. All applications which have registered this event will receive a notification when data is updated in the cache.

  • Remove Notification: Remove notification is triggered when an item is removed from the cache. All applications which have registered this event will receive a notification when data is removed from the cache.

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
  • Node.js
  • Python
  • Scala
  • Make sure that event notifications are enabled using NCache Web Manager.
  • Install either of the following NuGet packages in your application based on your NCahce edition:
    • Enterprise: Alachisoft.NCache.SDK
    • Professional: Alachisoft.NCache.Professional.SDK
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Events
    • Alachisoft.NCache.Runtime.Exceptions
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • For API details, refer to: ICache, RegisterCacheNotification, EventType, EventDataFilter, UnRegisterCacheNotification, CacheEventDescriptor.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Add the following Maven dependencies in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise Edition--> 
    <artifactId>ncache-client</artifactId>
    <!--for NCache Professional Edition-->
    <artifactId>ncache-professional-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your application:
  • import com.alachisoft.ncache.client.*;
  • import com.alachisoft.ncache.runtime.exceptions.*;
  • import com.alachisoft.ncache.runtime.events.*;
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • For API details, refer to: Cache, CacheDataModificationListener, CacheStatusEventListener, getEventType, removeCacheNotificationListener, CacheEventDescriptor.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Install and include either of the following modules in your application based on your NCache edition:
    • Enterprise: const ncache = require('ncache-client')
    • Professional: const ncache = require('ncache-professional-client')
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: Cache, CacheDataModificationListener, getEventType, removeCacheDataModificationListener.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Install the NCache Python client by executing the following command:
# Enterprise Client
pip install ncache-client

# Professional Client
pip install ncache-professional-client
  • Import the NCache module in your application.
  • Cache must be running.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Add the following Maven dependencies in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise Edition--> 
    <artifactId>ncache-scala-client</artifactId>
    <!--for NCache Professional Edition-->
    <artifactId>ncache-scala-professional-client</artifactId> 
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your application:
    • import com.alachisoft.ncache.scala.client.*;
    • import com.alachisoft.ncache.scala.runtime.events.*;
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.

Using Cache Level Events

Cache level notifications are generic events which will be triggered upon every execution of the appropriate registered event type. To register these events for notification, RegisterCacheNotification method is used. Appropriate EventType is used to restrict the cache for monitoring only the specific client operation. EventType includes the following:

  • ItemAdded: This event type is triggered when an item is being added.

  • ItemUpdated: This event type is triggered when an item is being updated.

  • ItemRemoved: This event type is triggered when an item is being removed.

EventDataFilter is specified to quantify the amount of information returned upon an event execution. Events that are registered then provide the user with the information based on these data filters. Following are the data filters that can be specified by the user.

  • None: On specifying this filter, only the affected keys are returned in the event notification.

  • MetaData: On specifying this filter, the affected keys along with their metadata are returned in the event notification. The metadata that is returned includes the groups and subgroups, cache item priority, provider name and the expiration of the items.

  • DataWithMetadata: On specifying this filter, the keys along with the metadata as well as their entire values are returned in the event notification.

For more details on data filters, please refer to the Events Overview section.

Important

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

Step 1: Implementing Callback for Event Notifications

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

Important
  • For Java, CacheDataModificationListener interface must be implemented with its methods.
  • An instance of the class implementing Java interface must be passed in order to get events.
  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
// 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
    }
}
// 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")
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.")
  }
}
Note

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

Step 2: Register Cache Notifications

After implementing the callbacks, 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 want. 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.

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

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
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 {
  // 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
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
    }
}
Note

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

Step 3: Unregistering 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 in order 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
  • Node.js
  • Python
  • Scala
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 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
try {
    // Unregister Notifications using the EventDescriptor
    cache.getMessagingService.removeCacheNotificationListener(eventDescriptor)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
Note

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

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