• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Cache Level Event Notifications

The Cache Level Event notifications are fired when data is added, updated, or removed in the cache from clients, Loader, Backing Source, etc. By default, the Cache Level Events are disabled (except for 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, 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
  • Legacy API
  • 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.
  • 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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
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;
        }
    }
}
// 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 as implemented by the user. The following example creates a method that registers callbacks for cache notifications with certain 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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// 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 and
    // 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

// 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");
}
# Precondition: Cache is already connected

# Events have been enabled through the NCache Management Center/Config Files

# Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType and
# EventDataFilter "None" 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)
// Precondition: Cache is already connected

// Events have been enabled through the NCache Management Center/Config Files

// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType and
// EventDataFilter "None" 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
);
// 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 and
    // 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 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
  • Legacy API
// 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. 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.

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Community
  • 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 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top