Item Level Event Notifications
Item Level Data Notifications can be used when you want to be notified about a limited set of data rather than every operation performed on cache.
For example, if the cache contains a large amount of data and gets notified every time any change occurs in the data set, which causes an overhead and the application's performance gets affected. To provide better performance for the application, you can select a particular data set and get notifications for that.
The cache will be responsible for monitoring changes for the specified chunk. Since the data set to be selected is already added in the cache, the cache provides notifications on performing the UPDATE or REMOVE operation.
Applications register callback method for a specific key in cache using API calls and get a notification when that key gets updated or removed from cache.
These Notifications are asynchronously sent to the client so there is no overhead on client’s activities.
Pre-Requisites
- Include the following namespaces in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.Events
Alachisoft.NCache.Runtime.Exceptions
- The application must be connected to cache before performing the operation.
- Cache must be running.
- 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.
Step 1: Register Callback for Event Notifications
First step is to register a callback for the multiple events. The example below shows how to register callbacks event notifications.
// Create a target method
public static void OnCacheDataModification(string key, CacheEventArg args)
{
switch (args.EventType)
{
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;
}
}
Recommendation: 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 Item Notifications
After registering the callbacks, a target method is created which contains multiple callbacks.
Appropriate
EventType is used to restrict the cache for monitoring only the specific client operation. Event type includes ItemUpdated
and ItemRemoved
event type that must be specified by a separate method call. Multiple event types can also be specified in a single method call.
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. It provides the entire data and metadata in the event notification.
For more detail please refer to the Events Overview section.
Note
The key must exist in cache for the event to be registered. Only update
or
remove
event types can be registered in item level events.
Register Item Notifications for a Particular Item
In order to register item notification for a single specified item, use the RegisterCacheNotifications method which takes a single key, the callback, the EventType and the EventDataFilter. For Java, CacheEventsListener is used to quantify the amount of information to be returned through event notifications.
The following example shows how to register item notifications with the ItemUpdated
event type for a particular item.
Note
If EventDataFilter
is not specified, EventDataFilter.None
is set automatically.
try
{
// PreCondition: Cache is already initialized
// Register target method
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register item notifications with 'ItemUpdated' event type
// EventDataFilter as DataWithMetadata which returns keys along with their
// entire data
cache.MessagingService.RegisterCacheNotification(key, dataNotificationCallback,
EventType.ItemUpdated,
EventDataFilter.DataWithMetadata);
// 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
}
Recommendation: 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 Notifications for a Specified Items
In order to register item notification for a chunk of specified item, use the RegisterCacheNotifications method which takes an array of keys, the EventType and the EventDataFilter.
The following example shows how to register item notifications with the ItemUpdated
and itemRemoved
event type for a particular item.
Note
If EventDataFilter
is not specified, EventDataFilter.None
is set automatically.
try
{
// PreCondition: Cache is already initialized
// Register target method
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Fetch all products from database
Product[] products = FetchProductsFromDB();
// Create a new array keys with the specified keys for which the cache
// fires notifications
string[] keys = new string[products.Length];
int index = 0;
foreach (var product in products)
{
// Generate a unique cache key for this product
keys[index] = $"Product:{product.ProductID}";
index++;
}
// Register item notifications with 'ItemUpdated' and 'ItemRemoved' event type
// EventDataFilter as DataWithMetadata which returns keys along with their
// entire data
cache.MessagingService.RegisterCacheNotification(keys, dataNotificationCallback,
EventType.ItemUpdated,
EventDataFilter.DataWithMetadata);
// 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
}
Recommendation: 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: Register Item Notifications Using CacheItem
CacheItem is a custom class provided by NCache which can be used to add data to the cache.
Item level events can also be registered with a particular key by registering as a property of CacheItem
.
SetCacheDataNotification method allows you to provide appropriate information for registering the notifications for the CacheItem
.
The example below registers item notifications for a cache item with the event type of ItemUpdated
and ItemRemoved
.
try
{
// PreCondition: Cache is already initialized
// Register target method
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Get Product from database against given ProductID
Product product = FetchProductFromDB("1001");
// Create a unique cache key for this product.
string key = $"Products:{product.ProductID}";
// Create a new CacheItem
var cacheItem = new CacheItem(product);
// 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);
//Re-inserts the cacheItem into cache with events registered
cache.Insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
Recommendation: 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: Unregister Item Level Notifications
You can also unregister a previously registered item level notification using the UnRegisterCacheNotification method if you don't want to receive further notifications. For Java, use the removeCacheDataModificationListener method to unregister the registered notfications.
Using this method, the appropriate key, callback CacheDataNotificationCallback
and EventType
must be specified.
Following example shows how to unregister notifications for a specific key.
try
{
// Unregister notifications for the ItemRemoved EventType for the
// particular key and specify the callback
cache.MessagingService.UnRegisterCacheNotification(key, new CacheDataNotificationCallback(OnItemRemovedCallback), EventType.ItemRemoved);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Additional Resources
For a full functioning .NET application executing events, you can use the sample shipped with NCache which is placed at:
- .NET Framework: %NCHOME%\samples\dotnet\Events
- .NET Core: %NCHOME%\samples\dotnetcore\Events
- Java: %NCHOME%\samples\java\Events
See Also
Cache Level Event Notifications
Pub/Sub Messaging
Search Cache with LINQ