项目级别事件通知
可以注册项目级事件通知以获取特定键的通知。除了按键之外,还可以使用以下命令来注册项目级别事件: CacheItem
班级。当对 sp 执行更新或删除操作时可以收到通知
重要
该密钥必须存在于缓存中才能注册事件。 只能为项目级别事件注册更新或删除事件类型。
注册Item Level Events的相关细节讨论如下。
先决条件
实现事件通知的回调
您可以为以下事件实现回调 EventType
根据用户的逻辑指定 ItemAdded
, ItemUpdated
或 ItemRemoved
事件。 下面的示例显示了如何为事件通知注册回调。
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")
备注
为确保操作是故障安全的,建议处理应用程序中的任何潜在异常,如中所述 处理故障.
注册项目通知
鉴于已实现回调,将创建一个包含多个回调的目标方法。 合适的 EventType
仅用于监视特定的客户端操作。 这些事件类型包括 ItemUpdated
和 ItemRemoved
必须通过单独的方法调用来指定。 EventDataFilter
指定用于量化事件执行时返回的信息量。
备注
If EventDataFilter
没有指定, EventDataFilter.None
是自动设置的。
在这里,我们解释了如何注册特定项目或一组项目的项目通知。
注册特定项目的项目通知
要注册单个项目的项目通知,请使用 RegisterCacheNotifications
通过提供单个密钥的方法, EventType
,并 EventDataFilter
. 以下示例显示如何使用 ItemUpdated
特定项目的事件类型。
// 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
)
为一组项目注册项目通知
要注册一组项目的项目通知,请使用 RegisterCacheNotifications
方法通过提供一个键数组, EventType
,并 EventDataFilter
. 以下示例显示如何使用 ItemUpdated
一组项目的事件类型。
// 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
使用 CacheItem 注册项目通知
CacheItem
是由提供的自定义类 NCache 可用于将数据添加到缓存。 Item Level Events 也可以通过使用 CacheItem.SetCacheDataNotification
方法。 此方法允许您提供适当的信息以注册通知 CacheItem
.
下面的例子注册 ItemUpdated
和 ItemRemoved
事件 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)
取消注册项目级别事件通知
您还可以使用以下命令注销之前注册的项目级事件通知: UnRegisterCacheNotification
如果您不想收到进一步的通知,请使用该方法。 对于 Java,使用 removeCacheDataModificationListener
注销已注册通知的方法。 使用此方法,适当的键,回调 CacheDataNotificationCallback
及 EventType
必须指定。
以下示例显示如何注销特定键的通知。
// 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]
更多资讯
NCache 为项目级别事件通知提供了一个示例应用程序 GitHub上.
参见
.NET: Alachisoft.NCache.运行时.事件 命名空间。
Java的: COM。alachisoft.ncache。事件 命名空间。
节点.js: 事件缓存项 类。
Python: ncache.runtime.caching.events 类。