アイテムレベルのイベント通知
アイテム レベルのイベント通知を登録して、特定のキーに関する通知を受け取ることができます。キーのほかに、アイテム レベルのイベントも、 CacheItem
クラス。 SP で更新または削除操作が実行されたときに通知を受け取ることができます。
重要
イベントを登録するには、キーがキャッシュに存在する必要があります。 項目レベルのイベントには、更新または削除のイベント タイプのみを登録できます。
項目レベルのイベントの登録に関する詳細については、以下で説明します。
前提条件
イベント通知のコールバックを実装する
イベントのコールバックを実装できます。 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")
Note
操作がフェイルセーフであることを保証するために、で説明されているように、アプリケーション内の潜在的な例外を処理することをお勧めします。 失敗の処理.
アイテム通知を登録する
コールバックが実装されているとすると、複数のコールバックを含むターゲット メソッドが作成されます。 適切な EventType
特定のクライアント操作のみを監視するために提供されています。 これらのイベント タイプには次のものがあります。 ItemUpdated
& ItemRemoved
これは別のメソッド呼び出しで指定する必要があります。 EventDataFilter
イベントの実行時に返される情報の量を定量化するために指定されます。
Note
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 これは、キャッシュにデータを追加するために使用できます。 項目レベルのイベントは、 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の.
も参照してください
。ネット: Alachisoft.NCache.ランタイム.イベント 名前空間
Java: comの。alachisoft.ncache.イベント 名前空間
Node.js: イベントキャッシュアイテム とに提供されます。
Python: ncache.runtime.caching.events とに提供されます。