캐시 수준 이벤트 알림
클라이언트, 로더, 백업 소스 등의 캐시에서 데이터가 추가, 업데이트 또는 제거되면 캐시 수준 이벤트 알림이 시작됩니다. 기본적으로 캐시 수준 이벤트는 비활성화되어 있으며(캐시 삭제 작업 제외) 다음을 통해 활성화할 수 있습니다. 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
. 이벤트는 적절한 리스너에게 통지되고 사용자가 구현한 대로 처리됩니다.
중대한
XNUMXD덴탈의 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
또한 알림 등록을 취소하도록 지정해야 합니다. 자바와 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 에서 캐시 수준 이벤트 알림에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.런타임.이벤트 네임 스페이스.
자바 : COM.alachisoft.ncache.이벤트 네임 스페이스.
Node.js : 이벤트 캐시 항목 클래스입니다.
파이썬 : ncache.runtime.caching.events 클래스입니다.