Try Playground
Show / Hide Table of Contents

Cache Level Event Notifications

The Cache Level Event notifications are fired when clients, Loaders, Backing Sources, or other sources add, modify, or remove data in the cache. By default, these notifications are disabled (with the exception of cache cleared events) and must be enabled manually via the NCache Management Center.

The Cache Level Event can be registered using the RegisterCacheNotification by specifying the implemented callback, EventType, and EventFilter. 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

  • .NET
  • Java
  • Python
  • Node.js
  • 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: 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 the NCache Management Center.
  • 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 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.

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.

  • .NET
  • Java
  • Python
  • Node.js
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) {
                    Customer updatedCustomer = args.getItem().getValue(Customer.class); // Ignore error code works
                    System.out.println("Updated Item: " + updatedCustomer);
                }
                break;

            case ItemRemoved:
                System.out.println("Item with Key '" + key + "' has been removed from the cache '" + args.getCacheName() + "'");
                break;
        }
        System.out.println("Completed");
    }
}

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")
// 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;
        }
    }
}
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 which can have multiple callbacks. The method contains an Event Type and 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, or DataWithMetadata. The events will be notified to their appropriate listeners and handled as implemented by the user.

Important

The 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 the EventDataFilter is not specified, the EventDataFilter.None is set automatically.

  • .NET
  • Java
  • Python
  • Node.js
public void RegisterCacheNotificationsForAllOperations()
{
    // create CacheDataNotificationCallback object
    var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);

    // Register cache notification with "ItemAdded" EventType and
    // EventDataFilter "None" which 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");
    }
}
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();

// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType and
// 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");
}
# Events have been enabled through the NCache Management Center/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)
// Events have been enabled through the NCache Management Center/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
);

Unregister Cache Level Events

The previously registered Cache Level Event Notifications can also be unregistered if they are no longer required using the UnRegisterCacheNotification method. Using this method, the CacheEventDescriptor also 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
  • Java
  • Python
  • Node.js
// Unregister Notifications using the EventDescriptor
cache.MessagingService.UnRegisterCacheNotification(eventDescriptor);
// Unregister Notifications using the EventDescriptor
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
# Unregister notifications using EventDescriptor
cache.get_messaging_service().remove_cache_notification_listener(event_descriptor)
// Unregister notifications using EventDescriptor
await cache.getMessagingService().removeCacheDataNotificationListener(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. The 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.

In This Article
  • Prerequisites
  • Implement Callback for Event Notifications
  • Register Cache Notifications
  • Unregister Cache Level Events
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top