Notifiche di eventi a livello di oggetto
Le notifiche di eventi a livello di articolo possono essere registrate per ricevere notifiche per chiavi specifiche. Oltre alle chiavi, gli eventi a livello di articolo possono anche essere registrati utilizzando CacheItem classe. Le notifiche vengono attivate quando si verificano operazioni di aggiornamento o rimozione sulle chiavi specificate. Gli eventi a livello di elemento vengono registrati utilizzando RegisterCacheNotification fornendo la richiamata implementata, EventTypee EventDataFilterDi seguito vengono illustrati i dettagli relativi alla registrazione degli eventi a livello di elemento.
Consigli
La chiave deve esistere nella cache affinché l'evento venga registrato. Solo la update and rimuovere è possibile registrare tipi di evento per eventi a livello di articolo.
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, CacheItem, Tipo di evento, EventDataFilter, RegisterCacheNotifica, UnRegisterCacheNotifica, CacheDataNotification Callback, Servizio di messaggistica, CacheEventArg, OttieniCacheItem, Notifica SetCacheData, inserire, Ottieni valore.
- 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, CacheItem, getEventType, EventDataFilter, Tipo di evento, CacheDataModificationListener, rimuoviCacheNotificationListener, addCacheNotificationListener, CacheEventArg, getMessagingService, EventCacheItem, getValore, getCacheItem, addCacheDataNotificationListener, insert, CacheEventDescriptor.
- 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, CacheItem, Tipo di evento, EventDataFilter, get_messaging_service, get_event_type, add_cache_notification_listener, rimuovi_cache_notification_listener, CacheEventArg, ottenere_nome_cache, ottenere_oggetto, EventCacheItem, ottieni_valore, get_cacheitem, aggiungi_listener_notifica_dati_cache, insert.
- 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.
Implementazione di gestori di eventi per modifiche dei dati a livello di elemento
È possibile implementare un callback per gli eventi a livello di elemento in cui EventType è specificato secondo la logica dell'utente per ItemUpdated or 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.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;
}
}
public class CacheDataModificationListenerImpl implements CacheDataModificationListener {
@Override
public void onCacheDataModified(String key, CacheEventArg args)
{
switch (args.getEventType())
{
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() + "' and price '" + updatedProduct.getUnitPrice());
}
break;
case ItemRemoved:
System.out.println("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_UPDATED:
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:
print(f"Item with Key '{key}' has been removed from the cache '{arg.get_cache_name()}'")
// Create a target method
async function onCacheDataModification(key, eventType, eventArgs)
{
switch (eventType)
{
case ncache.EventType.ItemUpdated:
console.log(`Item with Key '${key}' has been updated in the cache '${eventArgs.cacheName}'`);
// Item can be used if EventDataFilter is DataWithMetadata or Metadata
if (eventArgs.item != null)
{
// Perform operations
}
break;
case ncache.EventType.ItemRemoved:
console.log(`Item with Key '${key}' has been removed from the cache '${eventArgs.cacheName}'`);
break;
}
}
// Using NCache Enterprise 4.9.1
public void OnCacheDataModification(string key, CacheEventArg args)
{
switch (args.EventType)
{
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 le notifiche degli eventi a livello di articolo
Una volta implementato il callback, viene creato un metodo di destinazione che contiene uno o più callback. Il metodo appropriato EventType viene quindi fornito per monitorare solo le operazioni specifiche del client. Questi tipi di eventi includono ItemUpdated and ItemRemoved che deve essere specificato da una chiamata di metodo separata. Il EventDataFilter Specifica la quantità di informazioni restituite quando viene eseguito un evento. La sezione seguente spiega come registrare le notifiche a livello di elemento per un particolare elemento o un insieme di elementi.
Note:
In .NET, EventDataFilter.None Viene utilizzato per impostazione predefinita se il filtro viene omesso. Per le altre API client supportate, specificare esplicitamente il filtro dati evento richiesto.
Registra le notifiche degli articoli per un articolo particolare
Per registrare la notifica di un singolo articolo, utilizzare il file RegisterCacheNotification metodo fornendo un'unica chiave, la EventType EventDataFilter. L'esempio seguente mostra come registrare le notifiche degli articoli con il ItemUpdated tipo di evento per un particolare elemento.
try
{
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
string key = "Product:Chai";
// Create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// 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);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
try
{
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
String key = "Product:Chai";
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.getMessagingService().addCacheNotificationListener(key, dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
}
catch (OperationFailedException exception)
{
// Exception can occur due to:
// Connection failures
// Operation timeout
}
catch (Exception exception)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
try:
# Precondition: Cache is already connected
# Key of the cache item to be monitored on events
key = "Product:Chai"
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register notifications for a specific item being updated in cache
# EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.get_messaging_service().add_cache_notification_listener(
data_notification_callback,
[EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA,
key
)
except Exception as ex:
# Exception can occur due to:
# - Connection failures
# - Operation timeout
# - Invalid arguments
print("Operation failed: " + str(ex))
try
{
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
var key = "Product:Chai";
// 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);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated], ncache.EventDataFilter.DataWithMetadata);
}
catch (error) {
// Handle any errors
}
try
{
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Key of the cache item to be monitored on events
string key = "Product:Chai";
// Create CacheDataNotificationCallback object
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register notifications for a specific item being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.RegisterCacheNotification(key, dataNotificationCallback,
EventType.ItemRemoved | EventType.ItemUpdated,
EventDataFilter.DataWithMetadata);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
}
catch (Exception ex)
{
// Any generic exception like ArgumentException, ArgumentNullException
}
Registra le notifiche degli articoli per un insieme di articoli
Per registrare le notifiche degli articoli per una serie di articoli, utilizzare il file RegisterCacheNotification metodo fornendo un array di chiavi, il EventType EventDataFilter. L'esempio seguente mostra come registrare le notifiche degli articoli con il ItemUpdated tipo di evento per un insieme di elementi.
// Precondition: Cache is already connected
// 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(OnCacheDataModification);
// 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);
// Precondition: Cache is already connected
// 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
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register notifications for a specific set of items being updated in cache
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.getMessagingService().addCacheNotificationListener(List.of(keys), dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
# Precondition: Cache is already connected
# Array of keys for items that need to be monitored on events
keys = [ "Product:Chai", "Product:Coffee", "Product:Juice", "Product:Coke" ]
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register notifications for specific set of items being updated in cache
# EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache.get_messaging_service().add_cache_notification_listener(
data_notification_callback,
[EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA,
keys
)
// Precondition: Cache is already connected
// Array of keys for items that need to be monitored on events
let keys = [ 'Product:Chai', 'Product:Coffee', 'Product:Juice', 'Product:Coke' ];
// 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);
// Iterate over each key and register the notification listener
for (let key of keys)
{
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated], ncache.EventDataFilter.DataWithMetadata);
}
Registra le notifiche degli elementi utilizzando CacheItem
Migliori CacheItem è una classe personalizzata fornita da NCache che può essere utilizzato per aggiungere dati alla cache. Gli eventi a livello di elemento possono anche essere registrati con una chiave particolare utilizzando CacheItem.SetCacheDataNotification metodo. Questo metodo consente di fornire le informazioni appropriate per la registrazione delle notifiche per il CacheItemL'esempio seguente registra ItemUpdated and ItemRemoved eventi per a CacheItem.
// Precondition: Cache is already connected
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 CacheItem with ItemRemoved 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);
// Precondition: Cache is already connected
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
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register events with CacheItem with ItemRemoved and ItemUpdated EventType
// Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cacheItem.addCacheDataNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemRemoved, EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
// Re-inserts the cacheItem into cache with events registered
cache.insert(key, cacheItem);
# Precondition: Cache is already connected
key = "Product:Chai"
# Fetch item from cache
cache_item = cache.get_cacheitem(key)
if cache_item is None:
product = fetch_product_from_db("Chai")
cache_item = CacheItem(product)
# Create CacheDataNotificationCallback object
data_notification_callback = on_cache_data_modified
# Register events with CacheItem with ItemRemoved and ItemUpdated EventType
# Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
cache_item.add_cache_data_notification_listener(
data_notification_callback,
[EventType.ITEM_REMOVED, EventType.ITEM_UPDATED],
EventDataFilter.DATA_WITH_META_DATA
)
# Re-inserts the cacheItem into cache with events registered
cache.insert(key, cache_item)
// Precondition: Cache is already connected
let key="Product:Chai";
// Fetch item from cache
let cacheItem = await cache.getCacheItem(key);
if (cacheItem == null)
{
let product = await fetchProductFromDB("Chai");
cacheItem = new ncache.CacheItem(JSON.stringify(product));
}
// 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);
await messagingService.addCacheNotificationListener(key, eventListener, [ncache.EventType.ItemUpdated, ncache.EventType.ItemRemoved], ncache.EventDataFilter.DataWithMetadata);
// Re-insert the cacheItem into cache with events registered
await cache.insert(key, cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = cache.GetCacheItem(key);
if(cacheItem == null)
{
Product product = FetchProductFromDB("Chai");
cacheItem = new CacheItem(product);
}
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register events with CacheItem 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);
// 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 desideri ricevere ulteriori notifiche. Quando annulli la registrazione, devi specificare la chiave appropriata, callback CacheDataNotificationCallbacke EventTypeL'esempio seguente mostra come annullare la registrazione delle notifiche per una chiave specifica.
// Precondition: Cache is already connected
// Key of cached item to un-register events
string key = "Product:Chai";
// Callback method triggered on cache item events
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.MessagingService.UnRegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated);
// Precondition: Cache is already connected
// Callback method triggered on cache item events
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.None);
// Unregister notifications for the ItemUpdated EventType
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
# Precondition: Cache is already connected
# Key of cached item to un-register events
key = "Product:Chai"
# Callback method triggered on cache item events
data_notification_callback = on_cache_data_modified
# Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.get_messaging_service().remove_cache_notification_listener(
keys=key,
callablefunction=data_notification_callback,
eventtypes=[EventType.ITEM_UPDATED]
)
// Precondition: Cache is already connected
let key = "Product:Chai";
// Key of cached item to un-register events
let messagingService = await cache.getMessagingService();
// Callback method triggered on cache item events
let eventListener = new ncache.CacheDataModificationListener(onCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
await messagingService.removeCacheNotificationListener([key], eventListener, [ncache.EventType.ItemUpdated]);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Key of cached item to un-register events
string key = "Product:Chai";
// Callback method triggered on cache item events
CacheDataNotificationCallback dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Unregister notifications for the ItemUpdated EventType for particular key and specify the callback
cache.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.runtime.events pacchetto.
Pitone: eventi di caching di ncache.runtime modulo.
Node.js: EventCacheItem classe.