Notifiche di eventi a livello di cache
Le notifiche degli eventi a livello di cache vengono attivate quando i dati vengono aggiunti, aggiornati o rimossi dalla cache da client, Cache Loader, Backing Source, ecc. Queste notifiche consentono alle applicazioni di ricevere callback per le modifiche ai dati a livello di cache. Per impostazione predefinita, gli eventi a livello di cache sono disabilitati (ad eccezione dell'operazione di cancellazione della cache) e possono essere abilitati tramite NCache Centro di gestione.
L'evento del livello della cache può essere registrato utilizzando RegisterCacheNotification specificando il callback implementato, il necessario EventType EventDataFilter (Nessuno, Metadati o DataWithMetadata). Qui descriviamo come registrare e annullare la registrazione degli eventi a livello di cache.
Note:
L'applicazione non sarà in grado di ricevere eventi a meno che non si registri nella cache utilizzando la chiamata API di registrazione eventi specifica.
Prerequisiti
Prima di usare il NCache Per le API lato client, assicurarsi che siano soddisfatti i seguenti prerequisiti:
- Installa i seguenti pacchetti NuGet nella tua applicazione client .NET:
- Includere i seguenti spazi dei nomi nell'applicazione:
- La cache deve essere in esecuzione.
- Assicurati che i dati aggiunti lo siano serializzabile.
- Assicurati che abilita le notifiche degli eventi usando il NCache Centro Direzionale.
- Per i dettagli dell'API, fare riferimento a: ICache, RegisterCacheNotifica, Tipo di evento, EventDataFilter, UnRegisterCacheNotifica, CacheEventDescriptor, CacheDataNotification Callback, Servizio di messaggistica, CacheEventArg, Ottieni valore, È registrato.
- Aggiungi le seguenti dipendenze Maven per la tua applicazione client Java in
pom.xml file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Importa i seguenti pacchetti nell'applicazione client Java:
- La cache deve essere in esecuzione.
- Assicurati che i dati aggiunti lo siano serializzabile.
- Assicurati che abilita le notifiche degli eventi usando il NCache Centro Direzionale.
- Per i dettagli dell'API, fare riferimento a: Cache, CacheDataModificationListener, CacheEventDescriptor, rimuoviCacheNotificationListener, addCacheNotificationListener, Tipo di evento, EventDataFilter, getMessagingService, CacheEventArg, getEventType, getCacheName, getItem, EventCacheItem, getValore, getIsRegistered.
- Installa i seguenti pacchetti nella tua applicazione client Python:
- Importa i seguenti pacchetti nella tua applicazione:
- La cache deve essere in esecuzione.
- Assicurati che i dati aggiunti lo siano serializzabile.
- Assicurati che abilita le notifiche degli eventi usando il NCache Centro Direzionale.
- Per i dettagli dell'API, fare riferimento a: Cache, Tipo di evento, EventDataFilter, CacheEventDescriptor, get_messaging_service, CacheEventArg, add_cache_notification_listener, get_event_type, rimuovi_cache_notification_listener, ottenere_nome_cache, ottenere_oggetto, EventCacheItem, ottieni_valore, get_is_registered.
- Installa uno dei seguenti pacchetti NuGet nella tua applicazione client .NET:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Crea una nuova applicazione console.
- Assicurati che i dati aggiunti lo siano serializzabile.
- Aggiungi NCache Referenze individuando
%NCHOME%\NCache\bin\assembly\4.0 e aggiungendo Alachisoft.NCache.Web and Alachisoft.NCache.Runtime come appropriato.
- Includi il
Alachisoft.NCache.Web.Caching and Alachisoft.NCache.Runtime.Events spazi dei nomi nella tua applicazione.
- Per saperne di più sul NCache API legacy, scaricala NCache 4.9 documenti disponibili come file .zip file sul Alachisoft Sito web.
Implementare la richiamata per le notifiche di eventi
È possibile implementare un callback per gli eventi in cui EventType è specificato secondo la logica dell'utente per ItemAdded, ItemUpdatede ItemRemoved eventi. L'esempio seguente implementa un metodo di callback per le notifiche della cache con determinati tipi di evento.
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:
Per garantire che l'operazione sia a prova di errore, si consiglia di gestire eventuali potenziali eccezioni all'interno dell'applicazione, come spiegato in Gestione dei guasti.
Registra notifiche cache
Per registrare le notifiche a livello di cache, viene creato un metodo di destinazione che può avere più callback. Il metodo contiene un EventType and EventDataFilter. EventType viene regolato in base al tipo di operazione per la quale l'utente desidera ricevere notifiche. EventDataFilter può assumere uno dei tre valori possibili:
None
Metadata
DataWithMetadata
Gli eventi verranno notificati ai rispettivi listener e gestiti in base all'implementazione dell'utente. L'esempio seguente mostra come creare un metodo che registra callback per le notifiche della cache utilizzando tipi di evento specifici.
Consigli
Migliori EventDataFilter deve essere impostato con cura per evitare un consumo non necessario della larghezza di banda della rete.
Note:
In .NET, EventDataFilter.None viene utilizzato per impostazione predefinita quando il filtro viene omesso. Per le altre API client supportate, specificare esplicitamente il filtro dati evento richiesto.
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
try
{
// 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");
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
}
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
try
{
// 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");
}
}
catch (OperationFailedException exception)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception exception)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
}
# Precondition: Cache is already connected
def register_cache_notifications_for_all_operations(cache):
try:
# 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")
except Exception as ex:
# Handle generic exceptions (connection issues, invalid args, etc.)
print(f"Error occurred while registering cache notifications: {str(ex)}")
// Precondition: Cache is already connected
async function registerCacheNotificationsForAllOperations()
{
try
{
// 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);
}
catch (error) {
// Handle errors
}
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
public void RegisterCacheNotificationsForAllOperations()
{
try
{
// 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");
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception
}
}
Annulla registrazione notifiche cache
Le notifiche degli eventi a livello di cache precedentemente registrate possono essere annullate quando non sono più necessarie utilizzando UnRegisterCacheNotification metodo. Utilizzando questo metodo, il CacheEventDescriptor È inoltre necessario specificare se annullare la registrazione delle notifiche. Per Java e Node.js, utilizzare l'API Remove Notification Listener. L'esempio seguente mostra come annullare la registrazione delle notifiche utilizzando questo metodo.
// 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:
L'utilizzo di eventi a livello di cache potrebbe influire sulle prestazioni dell'applicazione poiché genera notifiche per tutte le operazioni specificate eseguite sull'intero set di dati della cache. Pertanto, l'utilizzo Eventi a livello di oggetto è l'approccio consigliato per evitare questo problema.
Risorse addizionali
NCache fornisce un'applicazione di esempio per le notifiche di eventi a livello di cache GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Eventi.di.runtime spazio dei nomi.
Giava: com.alachisoft.ncache.runtime.events pacchetto.
Pitone: eventi di caching di ncache.runtime modulo.
Node.js: EventCacheItem classe.