Notifications d'événement au niveau de l'article
Des notifications d'événements au niveau de l'élément peuvent être enregistrées pour recevoir des notifications pour des clés spécifiques. Outre les clés, les événements au niveau de l'objet peuvent également être enregistrés à l'aide du CacheItem
classe. Les notifications peuvent être reçues lorsque des opérations de mise à jour ou de suppression sont effectuées sur sp
Important
La clé doit exister dans le cache pour que l'événement soit enregistré. Seuls les types d'événements de mise à jour ou de suppression peuvent être enregistrés pour les événements au niveau de l'élément.
Les détails pertinents de l'enregistrement des événements au niveau de l'élément sont décrits ci-dessous.
Pré-requis
- Pour en savoir plus sur les prérequis standard requis pour travailler avec tous NCache fonctionnalités côté client, veuillez vous référer à la page donnée sur Prérequis de l'API côté client.
- Assurez-vous de activer les notifications d'événements utilisant l' NCache Centre de gestion.
- Pour plus de détails sur l'API, reportez-vous à : Cache, CacheItem, getEventType, Filtre de données d'événement, Type d'événement, CacheDataModificationListenerCacheDataModificationListener, RemoveCacheNotificationListener, addCacheNotificationListeneraddCacheNotificationListener, CacheDataModificationListenerCacheDataModificationListener.
- Pour en savoir plus sur les prérequis standard requis pour travailler avec tous NCache fonctionnalités côté client, veuillez vous référer à la page donnée sur Prérequis de l'API côté client.
- Assurez-vous de activer les notifications d'événements utilisant l' NCache Centre de gestion.
- Pour plus de détails sur l'API, reportez-vous à : Cache, CacheItem, Type d'événement, Filtre de données d'événement, supprimerDataModificationListener, getMessagingServicegetMessagingService, addCacheDataNotificationListeneraddCacheDataNotificationListener, CacheDataModificationListenerCacheDataModificationListener, getEventType.
- Pour en savoir plus sur les prérequis standard requis pour travailler avec tous NCache fonctionnalités côté client, veuillez vous référer à la page donnée sur Prérequis de l'API côté client.
- Assurez-vous de activer les notifications d'événements utilisant l' NCache Centre de gestion.
- Pour plus de détails sur l'API, reportez-vous à : Cache, CacheItem, Type d'événement, Filtre de données d'événement, get_messaging_service, get_event_type, add_cache_notification_listener, remove_cache_notification_listener, CacheEventArg.
Implémenter le rappel pour les notifications d'événements
Vous pouvez implémenter un rappel pour les événements où EventType
est spécifié selon la logique de l'utilisateur pour ItemAdded
, ItemUpdated
ou ItemRemoved
événements. L'exemple ci-dessous montre comment enregistrer des rappels pour les notifications d'événements.
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")
Notes
Pour garantir la sécurité de l'opération, il est recommandé de gérer toutes les exceptions potentielles au sein de votre application, comme expliqué dans Gestion des échecs.
Enregistrer les notifications d'articles
Étant donné que le rappel a été implémenté, une méthode cible est créée qui contient plusieurs rappels. Approprié EventType
est fourni pour surveiller uniquement les opérations spécifiques du client. Ces types d'événements incluent ItemUpdated
ainsi que ItemRemoved
qui doit être spécifié par un appel de méthode distinct. EventDataFilter
est spécifié pour quantifier la quantité d'informations renvoyées lors de l'exécution d'un événement.
Notes
If EventDataFilter
n'est pas spécifié, EventDataFilter.None
est réglé automatiquement.
Ici, nous expliquons comment vous pouvez enregistrer des notifications d'éléments pour un élément ou un ensemble d'éléments particulier.
Enregistrer les notifications d'article pour un article particulier
Pour enregistrer une notification d'élément pour un seul élément, utilisez le RegisterCacheNotifications
méthode en fournissant une clé unique, la EventType
, et le EventDataFilter
. L'exemple suivant montre comment enregistrer des notifications d'éléments avec le ItemUpdated
type d'événement pour un élément particulier.
// 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
)
Enregistrer les notifications d'articles pour un ensemble d'articles
Pour enregistrer des notifications d'éléments pour un ensemble d'éléments, utilisez l'outil RegisterCacheNotifications
méthode en fournissant un tableau de clés, la EventType
, et le EventDataFilter
. L'exemple suivant montre comment enregistrer des notifications d'éléments avec le ItemUpdated
type d'événement pour un ensemble d'éléments.
// 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
Enregistrer les notifications d'éléments à l'aide de CacheItem
CacheItem
est une classe personnalisée fournie par NCache qui peut être utilisé pour ajouter des données au cache. Les événements au niveau de l'élément peuvent également être enregistrés avec une clé particulière à l'aide de la CacheItem.SetCacheDataNotification
méthode. Cette méthode vous permet de fournir les informations appropriées pour enregistrer les notifications pour le CacheItem
.
L'exemple ci-dessous enregistre ItemUpdated
ainsi que ItemRemoved
événements pour 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)
Annuler l'enregistrement des notifications d'événements au niveau de l'élément
Vous pouvez également désenregistrer une notification d'événement au niveau de l'élément précédemment enregistrée à l'aide du UnRegisterCacheNotification
méthode si vous ne souhaitez plus recevoir de notifications. Pour Java, utilisez le removeCacheDataModificationListener
méthode pour désenregistrer les notifications enregistrées. En utilisant cette méthode, la clé appropriée, callback CacheDataNotificationCallback
et EventType
doit être spécifié.
L'exemple suivant montre comment annuler l'enregistrement des notifications pour une clé spécifique.
// 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]
Ressources additionnelles
NCache fournit un exemple d'application pour les notifications d'événement au niveau de l'élément sur GitHub.
Voir aussi
.RAPPORTER: Alachisoft.NCache.Runtime.Événements espace de noms.
Java: com.alachisoft.ncache.événements espace de noms.
Node.js : EventCacheItem classe.
python: ncache.runtime.caching.events classe.