Cache Level Event Notifications
The Cache Level Event notifications are fired when data is added, updated, or removed from the cache by clients, Cache Loader, Backing Source, etc. These notifications allow applications to receive callbacks for cache-wide data changes. By default, the Cache Level Events are disabled (except for the cache cleared operation) and can be enabled through the NCache Management Center.
The Cache Level Event can be registered using the RegisterCacheNotification by specifying the implemented callback, the required EventType, and the EventDataFilter (None, Metadata, or DataWithMetadata). Here, we describe how you can register and unregister the Cache Level Events.
Note
The application will not be able to receive events unless it registers itself against the cache using the specific event registration API call.
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, EventType, EventDataFilter, CacheEventDescriptor, get_messaging_service, CacheEventArg, add_cache_notification_listener, get_event_type, remove_cache_notification_listener.
- 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, CacheDataModificationListener, getEventType, removeCacheDataNotificationListener, getMessagingService, addCacheDataNotificationListener, EventType, getMessagingService, addCacheNotificationListener.
- 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 events where the 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.
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;
}
}
public class CacheDataModificationListenerImpl implements CacheDataModificationListener {
@Override
public void onCacheDataModified(String key, CacheEventArg args)
{
switch (args.getEventType())
{
case ItemAdded:
System.out.println("Item with Key '" + key + "' has been added to cache '" + args.getCacheName() + "'");
break;
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() + "', price '" + updatedProduct.getUnitPrice() + "', and quantity '" + updatedProduct.getQuantityPerUnit() + "'");
}
break;
case ItemRemoved:
System.out.println("Item with 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()
if event_type == EventType.ITEM_ADDED:
# Key has been added to cache
print(f"Item with Key '{key}' has been added to cache '{arg.get_cache_name()}'")
elif event_type == EventType.ITEM_UPDATED:
# Key has been updated in cache
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:
# Key has been removed from cache
print(f"Item with Key '{key}' has been removed from the cache '{arg.get_cache_name()}'")
// 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;
}
}
}
// Using NCache Enterprise 4.9.1
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 = (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 Cache Notifications
To register Cache Level Notifications, a target method is created that can have multiple callbacks. The method contains an EventType and EventDataFilter. The EventType is adjusted according to the type of operation the user wants to receive notifications for. The EventDataFilter can have one of the three possible values:
None
MetaData
DataWithMetadata
The events will be notified to their appropriate listeners and handled according to the user's implementation. The following example demonstrates how to create a method that registers callbacks for cache notifications using specific event types.
Important
The EventDataFilter must be carefully set to avoid unnecessary network bandwidth consumption.
Note
If the EventDataFilter is not specified, the EventDataFilter.None is set automatically.
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
// Create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType
// EventDataFilter "None" 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");
}
}
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType
// EventDataFilter "None" which means only keys will be returned
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemAdded, EventType.ItemUpdated, EventType.ItemRemoved), EventDataFilter.None);
if (eventDescriptor.getIsRegistered())
{
System.out.println("Cache level notifications registered successfully");
}
}
# Precondition: Cache is already connected
def register_cache_notifications_for_all_operations(cache):
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType
# EventDataFilter "None" means only keys will be returned
event_descriptor = cache.get_messaging_service().add_cache_notification_listener(data_notification_callback,
[EventType.ITEM_ADDED, EventType.ITEM_UPDATED, EventType.ITEM_REMOVED],
EventDataFilter.NONE
)
if event_descriptor.get_is_registered():
print("Cache level notifications registered successfully")
// Precondition: Cache is already connected
async function registerCacheNotificationsForAllOperations()
{
// 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);
await messagingService.addCacheDataNotificationListener(eventListener, [ncache.EventType.ItemAdded, ncache.EventType.ItemUpdated, ncache.EventType.ItemRemoved], ncache.EventDataFilter.DataWithMetadata);
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
// Create CacheDataNotificationCallback object
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType
// EventDataFilter "None" which means only keys will be returned
CacheEventDescriptor eventDescriptor = cache.RegisterCacheNotification(dataNotificationCallback,EventType.ItemAdded | EventType.ItemRemoved | EventType.ItemUpdated,EventDataFilter.None);
if (eventDescriptor.IsRegistered)
{
Console.WriteLine("Cache level notifications registered successfully");
}
}
Unregister Cache Notifications
The previously registered Cache Level Event Notifications can be unregistered when they are no longer required by using the UnRegisterCacheNotification method. Using this method, the CacheEventDescriptor also needs to be specified to unregister the notifications. For Java and Node.js, use the remove notification listener API. The following example shows how to unregister notifications using this method.
// Precondition: Cache is already connected
// Unregister Notifications using the EventDescriptor
cache.MessagingService.UnRegisterCacheNotification(eventDescriptor);
// Precondition: Cache is already connected
// Unregister Notifications using the EventDescriptor
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
# Precondition: Cache is already connected
# Unregister notifications using EventDescriptor
cache.get_messaging_service().remove_cache_notification_listener(event_descriptor)
// Precondition: Cache is already connected
// Unregister notifications using EventDescriptor
await cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Unregister notifications using EventDescriptor
cache.UnRegisterCacheNotification(eventDescriptor);
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. Hence, using 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
.NET: Alachisoft.NCache.Runtime.Events namespace.
Java: com.alachisoft.ncache.events namespace.
Python: ncache.runtime.caching.events class.
Node.js: EventCacheItem class.