キャッシュレベルのイベント通知
キャッシュ レベルのイベント通知は、クライアント、ローダー、バッキング ソースなどからキャッシュ内でデータが追加、更新、または削除されたときに発生します。デフォルトでは、キャッシュ レベルのイベントは無効になっており (キャッシュのクリア操作を除く)、 NCache 管理センター.
キャッシュ レベル イベントは次を使用して登録できます。 RegisterCacheNotification
実装されたコールバックを指定することで、 EventType
, EventFilter
。 ここでは、キャッシュ レベル イベントを登録および登録解除する方法について説明します。
Note
アプリケーションは、特定のイベント登録 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")
Note
操作がフェイルセーフであることを保証するために、で説明されているように、アプリケーション内の潜在的な例外を処理することをお勧めします。 失敗の処理.
キャッシュ通知の登録
キャッシュレベルの通知を登録するには、複数のコールバックを持つことができるターゲット メソッドが作成されます。 このメソッドには、イベント タイプとイベント フィルターが含まれています。 の EventType
ユーザーが通知を希望する操作の種類に応じて調整されます。 の EventDataFilter
可能な値は次の XNUMX つのうち XNUMX つです。 None
, MetaData
または DataWithMetadata
。 イベントは適切なリスナーに通知され、ユーザーによる実装に従って処理されます。
重要
EventDataFilter
不要なネットワーク帯域幅の消費を避けるために、慎重に設定する必要があります。
次の例では、特定のイベント タイプのキャッシュ通知のコールバックを登録するメソッドを作成します。
Note
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)
Note
キャッシュ レベル イベントを使用すると、キャッシュ データ セット全体に対して実行されるすべての指定された操作に対して通知が発行されるため、アプリケーションのパフォーマンスに影響を与える可能性があります。 アイテムレベルのイベント この問題を回避するには、推奨されるアプローチです。
その他のリソース
NCache キャッシュ レベル イベント通知のサンプル アプリケーションを提供します。 GitHubの.
も参照してください
。ネット: Alachisoft.NCache.ランタイム.イベント 名前空間
Java: comの。alachisoft.ncache.イベント 名前空間
Node.js: イベントキャッシュアイテム とに提供されます。
Python: ncache.runtime.caching.events とに提供されます。