• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
  • Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Download
  • Client Side API Programming
  • Events
  • Cache Level Events
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Dependency
      • Oracle Dependency
      • OleDB Dependency
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Overview
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Pub/Sub Topics
      • Publish Messages to a Topic
      • Subscribe to a Topic
      • Monitoring Pub/Sub Topics
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • SignalR Core Integration for NCache
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

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.

In This Article
  • Prerequisites
  • Implement Callback for Event Notifications
  • Register Cache Notifications
  • Unregister Cache Notifications
  • 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 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 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top