아이템 레벨 이벤트 알림
아이템 레벨 이벤트 알림을 등록하여 특정 키/키에 대한 알림을 받을 수 있습니다. 키 외에도 아이템 레벨 이벤트도 다음을 사용하여 등록할 수 있습니다. 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")
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
항목 알림 등록
콜백이 구현된 경우 여러 콜백을 포함하는 대상 메서드가 생성됩니다. 적절한 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 캐시에 데이터를 추가하는 데 사용할 수 있습니다. 항목 수준 이벤트는 다음을 사용하여 특정 키로 등록할 수도 있습니다. 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
더 이상 알림을 받지 않으려면 방법입니다. 자바의 경우 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.런타임.이벤트 네임 스페이스.
자바 : COM.alachisoft.ncache.이벤트 네임 스페이스.
Node.js : 이벤트 캐시 항목 클래스입니다.
파이썬 : ncache.runtime.caching.events 클래스입니다.