缓存级别事件通知
Cache-level event notifications are fired when data is added, updated, or removed in the cache from clients, Loader, Backing Source, etc. By default, Cache Level Events are disabled (except for cache cleared operation) and can be enabled through the NCache 管理中心.
缓存级别事件可以使用以下方式注册 RegisterCacheNotification
通过指定实现的回调, EventType
及 EventFilter
。 在这里,我们描述如何注册和取消注册缓存级别事件。
备注
应用程序将无法接收事件,除非它使用特定的事件注册 API 调用在缓存中注册自身。
先决条件
实现事件通知的回调
您可以为以下事件实现回调 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}', 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;
}
}
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");
}
}
// Create a target class
// Precondition: Events have been enabled
async onCacheDataModified(key, arg) {
if (null != arg.getEventType()) {
switch (arg.getEventType()) {
// perform operations
case ncache.EventType.ItemAdded:
// key has been added to cache
break;
case ncache.EventType.ItemUpdated:
// key has been updated in cache
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
根据用户想要其通知的操作类型进行调整。 这 EventDataFilter
可以具有以下三个可能值之一: None
, MetaData
或 DataWithMetadata
. 事件将被通知给相应的侦听器并由用户执行处理。
重要
EventDataFilter
必须小心设置,以避免不必要的网络带宽消耗。
以下示例创建一个方法,该方法为具有某些事件类型的缓存通知注册回调。
备注
If EventDataFilter
没有指定, EventDataFilter.None
是自动设置的。
public void RegisterCacheNotificationsForAllOperations()
{
// create CacheDataNotificationCallback object
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);
// Register cache notification with "ItemAdded" EventType and
// EventDataFilter "None" which means only keys will be returned
CacheEventDescriptor eventDescriptor = cache.MessagingService.RegisterCacheNotification(dataNotificationCallback, EventType.ItemAdded | EventType.ItemUpdated | EventType.ItemRemoved, EventDataFilter.None);
if (eventDescriptor.IsRegistered)
{
Console.WriteLine("Cache level notifications registered successfully");
}
}
// Create CacheDataNotificationCallback object
CacheDataModificationListener dataModificationListener = new CacheDataModificationListenerImpl();
// Register cache notification with "ItemAdded", "ItemUpdated", and "ItemRemoved" EventType and
// EventDataFilter "None" which means only keys will be returned
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(dataModificationListener, EnumSet.of(EventType.ItemAdded, EventType.ItemUpdated, EventType.ItemRemoved), EventDataFilter.None);
if (eventDescriptor.getIsRegistered()) {
System.out.println("Cache level notifications registered successfully");
}
// Events have been enabled through the NCache Management Center/Config Files
// Register cache notification with "ItemAdded" EventType and "None"
// EventDataFilter which means only keys will be returned
let eventListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);
let messagingService = await this.cache.getMessagingService();
await messagingService.addCacheNotificationListener(
eventListener,
ncache.EventType.ItemAdded,
ncache.EventDataFilter.None
);
// Register cache notifications and set the
// EventDataFilter as DataWithMetadata which returns keys along with their entire data
let EventListener = new ncache.CacheDataModificationListener(
this.onCacheDataModified,
this.onCacheCleared
);
let messagingService2 = await this.cache.getMessagingService();
let data = await messagingService2.addCacheNotificationListener(
eventListener,
ncache.EventType.ItemAdded,
ncache.EventDataFilter.DataWithMetadata
);
# Events have been enabled through the NCache Management Center/Config Files
# Register cache notification with "ItemAdded" EventType and "None"
# EventDataFilter which means only keys will be returned
messaging_service = cache.get_messaging_service()
messaging_service.add_cache_notification_listener(event_listener, [ncache.EventType.ITEM_ADDED], ncache.EventDataFilter.NONE)
# Register cache notifications and set the
# EventDataFilter as DataWithMetadata which returns keys along with their entire data
messaging_service_2 = cache.get_messaging_service()
messaging_service_2.add_cache_notification_listener(event_listener, [ncache.EventType.ITEM_ADDED], ncache.EventDataFilter.DATA_WITH_META_DATA)
取消注册缓存级别事件
如果不再需要使用先前注册的缓存级别事件通知,也可以取消注册它。 UnRegisterCacheNotification
方法。 使用这种方法, CacheEventDescriptor
还需要指定取消注册通知。 对于 Java 和 Node.js, removeCacheDataModificationListener
用于注销事件通知。
以下示例显示如何使用此方法取消注册通知。
// Unregister Notifications using the EventDescriptor
cache.MessagingService.UnRegisterCacheNotification(eventDescriptor);
// Unregister Notifications using the EventDescriptor
cache.getMessagingService().removeCacheNotificationListener(eventDescriptor);
// Unregister notifications using EventDescriptor
await cache.getMessagingService().removeCacheDataNotificationListener(eventDescriptor);
# Unregister notifications using EventDescriptor
cache.get_messaging_service().remove_cache_notification_listener(event_descriptor)
备注
使用缓存级别事件可能会影响应用程序的性能,因为它会针对在整个缓存数据集上执行的所有指定操作触发通知。 项目级别事件 是避免此问题的推荐方法。
更多资讯
NCache 为 Cache Level Event Notifications 提供了一个示例应用程序 GitHub上.
参见
.NET: Alachisoft.NCache.运行时.事件 命名空间。
Java的: COM。alachisoft.ncache。事件 命名空间。
节点.js: 事件缓存项 类。
Python: ncache.runtime.caching.events 类。