Notifiche di eventi a livello di oggetto
È possibile registrare le notifiche degli eventi a livello di elemento per ricevere notifiche per chiavi specifiche. Oltre alle chiavi, è possibile registrare anche eventi a livello di oggetto utilizzando il file CacheItem
classe. Le notifiche possono essere ricevute quando vengono eseguite operazioni di aggiornamento o rimozione su sp
Consigli
La chiave deve esistere nella cache affinché l'evento venga registrato. Solo i tipi di eventi di aggiornamento o rimozione possono essere registrati per gli eventi a livello di articolo.
I dettagli rilevanti della registrazione degli eventi a livello di articolo sono descritti di seguito.
Prerequisiti
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Assicurati che abilita le notifiche degli eventi usando il NCache Centro Direzionale.
- Per i dettagli dell'API, fare riferimento a: ICache, CacheItem, Tipo di evento, EventDataFilter, RegisterCacheNotifica , UnRegisterCacheNotifica, CacheDataNotification Callback.
Implementare la richiamata per le notifiche di eventi
È possibile implementare una richiamata per eventi in cui EventType
è specificato secondo la logica dell'utente per ItemAdded
, ItemUpdated
, o ItemRemoved
eventi. L'esempio seguente mostra come registrare le richiamate per le notifiche di eventi.
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}' with ID '{updatedProduct.ProductID}' and price '{updatedProduct.UnitPrice}'");
}
break;
case EventType.ItemRemoved:
Console.WriteLine($"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 le notifiche degli articoli
Dato che il callback è stato implementato, viene creato un metodo target che contiene più callback. L'appropriato EventType
è previsto per monitorare solo le operazioni specifiche del cliente. Questi tipi di eventi includono ItemUpdated
ed ItemRemoved
che deve essere specificato da una chiamata al metodo separata. EventDataFilter
è specificato per quantificare la quantità di informazioni restituite all'esecuzione di un evento.
Note:
If EventDataFilter
non è specificato, EventDataFilter.None
viene impostato automaticamente.
Qui spieghiamo come registrare le notifiche degli articoli per un particolare articolo o insieme di articoli.
Registra le notifiche degli articoli per un articolo particolare
Per registrare la notifica di un singolo articolo, utilizzare il file RegisterCacheNotifications
metodo fornendo un'unica chiave, la EventType
, e il EventDataFilter
. L'esempio seguente mostra come registrare le notifiche degli articoli con il ItemUpdated
tipo di evento per un particolare elemento.
// Key of the cache item to be monitored events
string key = "Product:Chai";
// create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataUpdation);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.MessagingService.RegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
// Callback to Update Event Notifications
public void OnCacheDataUpdation(string key, CacheEventArg args)
{
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}' with ID '{updatedProduct.ProductID}' and price '{updatedProduct.UnitPrice}'");
}
}
Registra le notifiche degli articoli per un insieme di articoli
Per registrare le notifiche degli articoli per una serie di articoli, utilizzare il file RegisterCacheNotifications
metodo fornendo un array di chiavi, il EventType
, e il EventDataFilter
. L'esempio seguente mostra come registrare le notifiche degli articoli con il ItemUpdated
tipo di evento per un insieme di elementi.
// Array of keys for items that need to be monitored on events
String[] keys = new String[]
{
"Product:Chai", "Product:Coffee", "Product:Juice", "Product:Coke"
};
// create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataUpdation);
// Register notifications for specific set of items being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.MessagingService.RegisterCacheNotification(keys, dataNotificationCallback, EventType.ItemUpdated, EventDataFilter.DataWithMetadata);
Registra le notifiche degli elementi utilizzando CacheItem
CacheItem
è una classe personalizzata fornita da NCache che può essere utilizzato per aggiungere dati alla cache. Gli eventi a livello di articolo possono anche essere registrati con una particolare chiave utilizzando il file CacheItem.SetCacheDataNotification
metodo. Questo metodo consente di fornire le informazioni appropriate per la registrazione delle notifiche per il CacheItem
.
L'esempio seguente registra ItemUpdated
ed ItemRemoved
eventi per a CacheItem
.
string key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = cache.GetCacheItem(key);
if(cacheItem == null)
{
Product product = FetchProductFromDB("Chai");
cacheItem = new CacheItem(product);
}
// create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// 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);
Annulla la registrazione delle notifiche di eventi a livello di articolo
È inoltre possibile annullare la registrazione di una notifica di evento a livello di articolo precedentemente registrata utilizzando UnRegisterCacheNotification
metodo se non vuoi ricevere ulteriori notifiche. Per Java, usa il removeCacheDataModificationListener
metodo per annullare la registrazione delle notifiche registrate. Usando questo metodo, la chiave appropriata, callback CacheDataNotificationCallback
e EventType
deve essere specificato.
L'esempio seguente mostra come annullare la registrazione delle notifiche per una chiave specifica.
// Key of cached item to un-register events
string key = "Product:Chai";
// callback method triggered on cache item events
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataUpdation);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.MessagingService.UnRegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated);
Risorse addizionali
NCache fornisce un'applicazione di esempio per le notifiche di eventi a livello di articolo GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Eventi.di.runtime spazio dei nomi.
Giava: com.alachisoft.ncache.eventi spazio dei nomi.
Node.js: EventCacheItem classe.
Pitone: ncache.runtime.caching.events classe.