Notificaciones de eventos a nivel de artículo
Las notificaciones de eventos a nivel de elemento se pueden registrar para recibir notificaciones de claves específicas. Además de las claves, los eventos de nivel de artículo también se pueden registrar utilizando el CacheItem
clase. Las notificaciones se pueden recibir cuando se realizan operaciones de actualización o eliminación en sp
Importante:
La clave debe existir en la memoria caché para que se registre el evento. Solo los tipos de eventos de actualización o eliminación se pueden registrar para eventos de nivel de artículo.
Los detalles relevantes del registro de eventos a nivel de elemento se analizan a continuación.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Asegúrese de habilitar notificaciones de eventos usando el NCache Centro de Gestión.
- Para obtener detalles de la API, consulte: cache, Artículo de caché, obtener tipo de evento, Filtro de datos de evento, Tipo de evento, CacheDataModificationListener, eliminarCacheNotificationListener, agregarCacheNotificationListener, CacheDataModificationListener.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Asegúrese de habilitar notificaciones de eventos usando el NCache Centro de Gestión.
- Para obtener detalles de la API, consulte: cache, Artículo de caché, Tipo de evento, Filtro de datos de evento, eliminarDataModificationListener, obtener servicio de mensajería, addCacheDataNotificationListener, CacheDataModificationListener, obtener tipo de evento.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Asegúrese de habilitar notificaciones de eventos usando el NCache Centro de Gestión.
- Para obtener detalles de la API, consulte: cache, Artículo de caché, Tipo de evento, Filtro de datos de evento, get_messaging_service, get_event_type, add_cache_notification_listener, remove_cache_notification_listener, CachéEventArg.
Implementar devolución de llamada para notificaciones de eventos
Puede implementar una devolución de llamada para eventos donde EventType
se especifica de acuerdo con la lógica del usuario para ItemAdded
, ItemUpdated
o ItemRemoved
eventos. El siguiente ejemplo muestra cómo registrar devoluciones de llamadas para notificaciones de eventos.
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;
}
}
// Precondition: Events have been enabled
// Create a target method
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");
}
}
// Precondition: Events have been enabled
// Create a target method
onCacheDataModified(key, arg)
{
if (null != arg.getEventType())
{
switch (arg.getEventType())
{
// perform operations
case ncache.EventType.ItemUpdated:
// key has been updated in cache
if (args.getItem() != null)
{
Product updateProduct = args.getItem().getValue();
// perform operations
}
break;
case ncache.EventType.ItemRemoved:
// key has been removed from cache
break;
default:
break;
}
}
}
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")
Note
Para garantizar que la operación sea a prueba de fallas, se recomienda manejar cualquier posible excepción dentro de su aplicación, como se explica en Manejo de fallas.
Registrar notificaciones de artículos
Dado que se ha implementado la devolución de llamada, se crea un método de destino que contiene varias devoluciones de llamada. La Apropiada EventType
se proporciona para monitorear solo las operaciones específicas del cliente. Estos tipos de eventos incluyen ItemUpdated
y ItemRemoved
que debe especificarse mediante una llamada a un método independiente. EventDataFilter
se especifica para cuantificar la cantidad de información devuelta tras la ejecución de un evento.
Note
If EventDataFilter
no está especificado, EventDataFilter.None
se establece automáticamente.
Aquí explicamos cómo puede registrar notificaciones de artículos para un artículo o conjunto de artículos en particular.
Registrar notificaciones de artículos para un artículo en particular
Para registrar una notificación de artículo para un solo artículo, utilice el RegisterCacheNotifications
método proporcionando una sola clave, la EventType
, y la EventDataFilter
. El siguiente ejemplo muestra cómo registrar notificaciones de artículos con el ItemUpdated
tipo de evento para un elemento en particular.
// 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}'");
}
}
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);
System.out.println("Item level notifications registered successfully for key: " + key);
key = "Product:1001"
# Register item notifications with 'ITEM_UPDATED' event type
# EventDataFilter as DATA_WITH_META_DATA which returns keys along with their
# entire data
messaging_service = cache.get_messaging_service()
messaging_service.add_cache_notification_listener(
event_listener,
[ncache.EventType.ITEM_UPDATED],
ncache.EventDataFilter.DATA_WITH_META_DATA,
key
)
Registrar notificaciones de artículos para un conjunto de artículos
Para registrar notificaciones de artículos para un conjunto de artículos, utilice el RegisterCacheNotifications
método proporcionando una matriz de claves, el EventType
, y la EventDataFilter
. El siguiente ejemplo muestra cómo registrar notificaciones de artículos con el ItemUpdated
tipo de evento para un conjunto de elementos.
// 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);
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
for (String key : keys) {
cache.getMessagingService().addCacheNotificationListener(key, dataModificationListener, EnumSet.of(EventType.ItemUpdated), EventDataFilter.DataWithMetadata);
}
System.out.println("Item level notifications registered successfully for the set of keys.");
let dataModificationListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);
// Fetch all products from database
let products = this.fetchProductsFromDB();
// Create a new array keys with the specified keys for which the cache fires notifications
let keys = new String[products.length]();
var index = 0;
products.forEach((element) => {
keys[index] = "Product:1001";
index++;
});
// Register item notifications with 'ItemUpdated' and 'ItemRemoved' event type
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
let messagingService = await this.cache.getMessagingService();
await messagingService.addCacheNotificationListener(
keys,
dataModificationListener,
ncache.EventType.ItemUpdated,
ncache.EventDataFilter.DataWithMetadata
);
# Register target method
data_modification_listener = event_listener
# Fetch all products from database
products = fetch_products_from_db()
# Create a array keys with the specified keys for which the cache
# fires notifications
keys = []
for product in products:
keys.append("Product:" + str(product.get_product_id()))
# Register item notifications with 'ITEM_UPDATED' and 'ITEM_REMOVED' event type
# EventDataFilter as DATA_WITH_META_DATA which returns keys along with their
# entire data
messaging_service = cache.get_messaging_service()
messaging_service.add_cache_notification_listener(
data_modification_listener,
[ncache.EventType.ITEM_UPDATED],
ncache.EventDataFilter.DATA_WITH_META_DATA,
keys
Registrar notificaciones de elementos mediante CacheItem
CacheItem
es una clase personalizada proporcionada por NCache que se puede utilizar para agregar datos a la memoria caché. Los eventos de nivel de elemento también se pueden registrar con una clave particular mediante el CacheItem.SetCacheDataNotification
método. Este método le permite proporcionar la información adecuada para el registro de las notificaciones para el CacheItem
.
El siguiente ejemplo registra ItemUpdated
y ItemRemoved
eventos para un 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);
String key = "Product:Chai";
// Fetch item from cache
CacheItem cacheItem = null;
cacheItem = cache.getCacheItem(key);
if (cacheItem == null) {
Customer customer = Customer.fetchCustomerFromDB("Customer:ALFKI");
cacheItem = new CacheItem(customer);
}
// 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);
System.out.println("CacheItem inserted successfully");
let eventListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);
let messagingService = await this.cache.getMessagingService();
await messagingService.addCacheNotificationListener(
"key",
eventListener,
ncache.EventType.ItemAdded,
ncache.EventDataFilter.Metadata
);
// Get Product from database against given ProductID
let products = this.fetchProductsFromDB();
// Create a unique cache key for this customer.
let key = "Product:1001";
// Register events with CaceItem with Item Removed and ItemUpdated EventType
// Set the EventDataFilter as DataWithMetadata which returns keys along with their entire data
let messagingService2 = await this.cache.getMessagingService();
await messagingService2.addCacheNotificationListener(
eventListener,
ncache.EventType.ItemAdded,
ncache.EventType.ItemRemoved,
ncache.EventType.ItemUpdated,
ncache.EventDataFilter.Metadata
);
let cacheItem = ncache.CacheItem;
//Inserts the cacheItem into cache with events registered
this.cache.insert(key, cacheItem);
# Get Product from database
product = fetch_product_from_db()
# Create a unique cache key for this product.
key = "Product:1001"
# Register events with CacheItem with ITEM_REMOVED and ITEM_UPDATED EventType
# Set the EventDataFilter as DATA_WITH_META_DATA which returns keys along with their entire data
cache_item = ncache.CacheItem(product)
cache_item.add_cache_data_notification_listener(
event_listener,
[ncache.EventType.ITEM_REMOVED, ncache.EventType.ITEM_UPDATED],
ncache.EventDataFilter.DATA_WITH_META_DATA
)
# Inserts the cacheItem into cache with events registered
cache.insert(key, cache_item)
Cancelar el registro de notificaciones de eventos de nivel de artículo
También puede cancelar el registro de una notificación de evento de nivel de artículo previamente registrada utilizando el UnRegisterCacheNotification
si no desea recibir más notificaciones. Para Java, use el removeCacheDataModificationListener
método para dar de baja las notificaciones registradas. Usando este método, la tecla apropiada, devolución de llamada CacheDataNotificationCallback
y EventType
debe especificarse.
El siguiente ejemplo muestra cómo anular el registro de notificaciones para una clave específica.
// 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);
// Unregister notifications for the ItemRemoved EventType for particular key and specify callback
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemAdded), EventDataFilter.None);
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
let eventListener;
// Unregister notifications for the ItemRemoved EventType for the
// particular key and specify the callback
await this.cache.removeCacheNotificationListener(
"key",
eventListener,
ncache.EventType.ItemRemoved
);
# Unregister notifications for the ITEM_REMOVED EventType for the
# particular key and specify the callback
cache.get_messaging_service().remove_cache_notification_listener
keys="key",
callablefunction=event_listener,
eventtypes=[ncache.EventType.ITEM_REMOVED]
Recursos adicionales
NCache proporciona una aplicación de muestra para notificaciones de eventos a nivel de artículo en GitHub.
Vea también
.NETO: Alachisoft.NCache.Eventos.en.tiempo.de.ejecución espacio de nombres
Java: com.alachisoft.ncache.eventos espacio de nombres
Nodo.js: Elemento de caché de evento clase.
Pitón: ncache.eventos.de.almacenamiento.en.caché en tiempo de ejecución clase.