Item Level Event Notifications
The Item Level Event Notifications can be registered to get notifications for specific key/keys. Besides keys, the Item Level Events can also be registered using the CacheItem class. Notifications are triggered when update or remove operations occur on the specified keys. The Item Level Events are registered using the RegisterCacheNotification by providing the implemented callback, EventType, and EventDataFilter. The relevant details of registering Item Level Events are discussed, as follows.
Important
The key must exist in the cache for the event to be registered. Only the update and remove event types can be registered for Item Level Events.
Prerequisites
- 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 the NCache Management Center.
- For API details, refer to: Cache, CacheItem, getEventType, EventDataFilter, EventType, CacheDataModificationListener, removeCacheNotificationListener, addCacheNotificationListener, CacheDataModificationListener.
- 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 the NCache Management Center.
- For API details, refer to: Cache, CacheItem, EventType, EventDataFilter, get_messaging_service, get_event_type, add_cache_notification_listener, remove_cache_notification_listener, 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 the NCache Management Center.
- For API details, refer to: Cache, CacheItem, EventType, EventDataFilter, removeDataModificationListener, getMessagingService, addCacheDataNotificationListener, CacheDataModificationListener, getEventType.
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Professional:
Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
- Create a new Console Application.
- Make sure that the data being added is serializable.
- Add NCache References by locating
%NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
- Include the
Alachisoft.NCache.Web.Caching and Alachisoft.NCache.Runtime.Events namespaces in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
Implement Callback for Event Notifications
You can implement a callback for Item Level Events where the EventType is specified according to the user's logic for ItemUpdated or ItemRemoved events. The example below shows how to register callbacks for event notifications.
public void OnCacheDataModification(string key, CacheEventArg args)
{
switch (args.EventType)
{
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}' with ID '{updatedProduct.ProductID}' and price '{updatedProduct.UnitPrice}'");
}
break;
case EventType.ItemRemoved:
Console.WriteLine($"Key '{key}' has been removed from the cache '{args.CacheName}'");
break;
}
}
public class CacheDataModificationListenerImpl implements CacheDataModificationListener {
@Override
public void onCacheDataModified(String key, CacheEventArg args)
{
switch (args.getEventType())
{
case ItemUpdated:
System.out.println("Item with Key '" + key + "' has been updated in the cache '" + args.getCacheName() + "'");
// Item can be used if EventDataFilter is DataWithMetadata or Metadata
if (args.getItem() != null)
{
Product updatedProduct = args.getItem().getValue(Product.class);
System.out.println("Updated Item is a Product having name '" + updatedProduct.getProductName() + "' and price '" + updatedProduct.getUnitPrice());
}
break;
case ItemRemoved:
System.out.println("Key '" + key + "' has been removed from the cache '" + args.getCacheName() + "'");
break;
}
}
}
def on_cache_data_modified(key: str, arg: CacheEventArg):
event_type = arg.get_event_type()
elif event_type == EventType.ITEM_UPDATED:
print(f"Item with Key '{key}' has been updated in the cache '{arg.get_cache_name()}'")
# Item can be used if EventDataFilter is DataWithMetadata or Metadata
if arg.get_item() is not None:
updated_customer = arg.get_item().get_value(Customer)
print(f"Updated Item is a Customer having name '{updated_customer.get_name()}', ID '{updated_customer.get_customer_id()}'")
elif event_type == EventType.ITEM_REMOVED:
print(f"Item with Key '{key}' has been removed from the cache '{arg.get_cache_name()}'")
// Create a target method
async function onCacheDataModification(key, eventType, eventArgs)
{
switch (eventType)
{
case ncache.EventType.ItemUpdated:
console.log(`Item with Key '${key}' has been updated in the cache '${eventArgs.cacheName}'`);
// Item can be used if EventDataFilter is DataWithMetadata or Metadata
if (eventArgs.item != null)
{
// Perform operations
}
break;
case ncache.EventType.ItemRemoved:
console.log(`Item with Key '${key}' has been removed from the cache '${eventArgs.cacheName}'`);
break;
}
}
// Using NCache Enterprise 4.9.1
public void OnCacheDataModification(string key, CacheEventArg args)
{
switch (args.EventType)
{
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 = (Product)args.Item.Value;
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;
}
}
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 Item Level Event Notifications
Once the callback has been implemented, a target method is created which contains one or more callbacks. The appropriate EventType is then provided for monitoring only the specific client operations. These event types include ItemUpdated and ItemRemoved which must be specified by a separate method call. The EventDataFilter specifies how much information is returned when an event is executed. The following section explains how to register Item Level Notifications for a particular item or a set of items.
Note
If the EventDataFilter is not specified, the EventDataFilter.None is set automatically.
Register Item Notifications for a Particular Item
To register item notification for a single item, use the RegisterCacheNotifications method by providing a single key, the EventType, and the EventDataFilter. The following example shows how to register item notifications with the ItemUpdated event type for a particular item.
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
string key = "Product:Chai";
// Create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.MessagingService.RegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
String key = "Product:Chai";
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.getMessagingService().addCacheNotificationListener(key, dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
# Precondition: Cache is already connected
# Key of the cache item to be monitored on events
key = "Product:Chai"
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register notifications for a specific item being updated in cache
# EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.get_messaging_service().add_cache_notification_listener(
data_notification_callback,
[EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA,
key
)
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
var key = "Product:Chai";
// Get the messaging service from the cache
let messagingService = await cache.getMessagingService();
// Create an event listener with callbacks for cache modification and cache clearance
let eventListener = new ncache.CacheDataModificationListener(onCacheDataModification, onCacheCleared);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated], ncache.EventDataFilter.DataWithMetadata);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
string key = "Product:Chai";
// Create CacheDataNotificationCallback object
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.RegisterCacheNotification(key, dataNotificationCallback,
EventType.ItemRemoved | EventType.ItemUpdated,
EventDataFilter.DataWithMetadata);
Register Item Notifications for a Set of Items
To register item notifications for a set of items, use the RegisterCacheNotifications method by providing an array of keys, the EventType, and the EventDataFilter. The following example shows how to register item notifications with the ItemUpdated event type for a set of items.
// Precondition: Cache is already connected
// Array of keys for items that need to be monitored on events
String[] keys = new String[]
{
"Product:Chai", "Product:Coffee", "Product:Juice", "Product:Coke"
};
// Create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register notifications for specific set of items being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.MessagingService.RegisterCacheNotification(keys, dataNotificationCallback, EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
// Precondition: Cache is already connected
// Array of keys for items that need to be monitored on events
String[] keys = new String[]
{
"Product:Chai", "Product:Coffee", "Product:Juice", "Product:Coke"
};
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register notifications for a specific set of items being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.getMessagingService().addCacheNotificationListener(List.of(keys), dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
# Precondition: Cache is already connected
# Array of keys for items that need to be monitored on events
keys = [ "Product:Chai", "Product:Coffee", "Product:Juice", "Product:Coke" ]
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register notifications for specific set of items being updated in cache
# EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.get_messaging_service().add_cache_notification_listener(
data_notification_callback,
[EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA,
keys
)
// Precondition: Cache is already connected
// Array of keys for items that need to be monitored on events
let keys = [ 'Product:Chai', 'Product:Coffee', 'Product:Juice', 'Product:Coke' ];
// Get the messaging service from the cache
let messagingService = await cache.getMessagingService();
// Create an event listener with callbacks for cache modification and cache clearance
let eventListener = new ncache.CacheDataModificationListener(onCacheDataModification, onCacheCleared);
// Iterate over each key and register the notification listener
for (let key of keys)
{
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated], ncache.EventDataFilter.DataWithMetadata);
}
Register Item Notifications Using CacheItem
The CacheItem is a custom class provided by NCache which can be used to add data to the cache.
The Item Level Events can also be registered with a particular key by using the CacheItem.SetCacheDataNotification method. This method allows you to provide the appropriate information for registering the notifications for the CacheItem. The example below registers ItemUpdated and ItemRemoved events for a CacheItem.
// Precondition: Cache is already connected
string key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = cache.GetCacheItem(key);
if(cacheItem == null)
{
Product product = FetchProductFromDB("Chai");
cacheItem = new CacheItem(product);
}
// Create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register events with CacheItem with ItemRemoved and ItemUpdated EventType
// Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cacheItem.SetCacheDataNotification(dataNotificationCallback, EventType.ItemRemoved | EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
// Re-inserts the cacheItem into cache with events registered
cache.Insert(key, cacheItem);
// Precondition: Cache is already connected
String key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = cache.getCacheItem(key);
if (cacheItem == null)
{
Product product = FetchProductFromDB("Chai");
cacheItem = new CacheItem(product);
}
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register events with CacheItem with ItemRemoved and ItemUpdated EventType
// Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cacheItem.addCacheDataNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemRemoved, EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
// Re-inserts the cacheItem into cache with events registered
cache.insert(key, cacheItem);
# Precondition: Cache is already connected
key = "Product:Chai"
# Fetch item from cache
cache_item = cache.get_cacheitem(key)
if cache_item is None:
product = fetch_product_from_db("Chai")
cache_item = CacheItem(product)
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register events with CacheItem with ItemRemoved and ItemUpdated EventType
# Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache_item.add_cache_data_notification_listener(
data_notification_callback,
[EventType.ITEM_REMOVED, EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA
)
# Re-inserts the cacheItem into cache with events registered
cache.insert(key, cache_item)
// Precondition: Cache is already connected
let key="Product:Chai";
// Fetch item from cache
let cacheItem = await cache.getCacheItem(key);
if (cacheItem == null)
{
let product = await fetchProductFromDB("Chai");
cacheItem = new ncache.CacheItem(JSON.stringify(product));
}
// Get the messaging service from the cache
let messagingService = await cache.getMessagingService();
// Create an event listener with callbacks for cache modification and cache clearance
let eventListener = new ncache.CacheDataModificationListener(onCacheDataModification);
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated, ncache.EventType.ItemRemoved], ncache.EventDataFilter.DataWithMetadata);
// Re-insert the cacheItem into cache with events registered
await cache.insert(key, cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = cache.GetCacheItem(key);
if(cacheItem == null)
{
Product product = FetchProductFromDB("Chai");
cacheItem = new CacheItem(product);
}
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register events with CaceItem with Item Removed and ItemUpdated EventType
// Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cacheItem.SetCacheDataNotification(dataNotificationCallback, EventType.ItemRemoved | EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
// Inserts the cacheItem into cache with events registered
cache.Insert(key, cacheItem);
Unregister Item Level Event Notifications
You can also unregister a previously registered Item Level Event Notification using the UnRegisterCacheNotification method if you don't want to receive further notifications. For Java, use the removeCacheDataModificationListener method to unregister the registered notifications. When unregistering, you must specify the appropriate key, callback CacheDataNotificationCallback, and EventType. The following example shows how to unregister notifications for a specific key.
// Precondition: Cache is already connected
// Key of cached item to un-register events
string key = "Product:Chai";
// Callback method triggered on cache item events
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.MessagingService.UnRegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated);
// Precondition: Cache is already connected
// Callback method triggered on cache item events
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.None);
// Unregister notifications for the ItemUpdated EventType
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
# Precondition: Cache is already connected
# Key of cached item to un-register events
key = "Product:Chai"
# Callback method triggered on cache item events
data_notification_callback = on_cache_data_modified
# Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.get_messaging_service().remove_cache_notification_listener(
keys=key,
callablefunction=data_notification_callback,
eventtypes=[EventType.ITEM_UPDATED]
)
// Precondition: Cache is already connected
let key = "Product:Chai";
// Key of cached item to un-register events
let messagingService = await cache.getMessagingService();
// Callback method triggered on cache item events
let eventListener = new ncache.CacheDataModificationListener(onCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
await messagingService.removeCacheNotificationListener([key], eventListener, [ncache.EventType.ItemUpdated]);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Key of cached item to un-register events
string key = "Product:Chai";
// Callback method triggered on cache item events
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.UnRegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated);
Additional Resources
NCache provides a sample application for Item Level Event Notifications on GitHub.
See Also
.NET: Alachisoft.NCache.Runtime.Events namespace.
Java: com.alachisoft.ncache.events namespace.
Python: ncache.runtime.caching.events class.
Node.js: EventCacheItem class.