캐시의 카운터 동작 및 사용
카운터는 단일 긴 값 데이터 구조 캐시에 저장됩니다. 값을 증가시키거나 감소시키고, 잠그거나, 이벤트를 등록할 수 있습니다. 예를 들어, 소셜 미디어 사이트에서 동영상이 조회될 때마다 조회수를 저장하는 카운터를 만들 수 있습니다. 또한 웹사이트에서 구독 또는 구독 취소를 할 때 구독자 수를 저장하는 데에도 사용할 수 있습니다. NCache 다음을 제공하여 이 카운터를 더욱 향상시킵니다. NCache-다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성, 그리고 더. 예를 들어 그룹에 대한 카운터를 지정할 수 있습니다. 구독정보 여기에는 고객 개체와 구독 카운터가 포함될 수 있습니다.
행동
- Null은 지원되는 값 유형이 아닙니다.
- 카운터의 이름이 지정됩니다. 따라서 카운터에 대해 고유한 캐시 키를 제공해야 합니다.
사전 조건
사용하기 전에 NCache 클라이언트 측 API를 사용할 때 다음 전제 조건을 충족하는지 확인하십시오.
- .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
- 기업: Alachisoft.NCache.SDK
- 오픈 소스: Alachisoft.NCache오픈소스 SDK
- 애플리케이션에 다음 네임스페이스를 포함합니다.
- 캐시가 실행 중이어야 합니다.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 아이캐시, 아이카운터, IDataTypeManager, 카운터 생성, 값 설정, 증가, 증분 기준, 감소, 감소 기준, 카운터 가져오기, ICollectionManager, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다, 데이터 유형 관리자, 데이터 유형 이벤트 인수.
카운터 생성
다음 코드 샘플은 다음을 사용하여 캐시에서 카운터를 생성하는 방법을 보여줍니다. CreateCounter 캐시 키에 대해 구독 카운터.
팁
당신은 또한 수 검색 가능한 속성 구성 그룹/태그/명명된 태그와 같은 무효화 속성 데이터 구조를 생성하는 동안 만료/퇴거/종속성과 같은.
try
{
// Precondition: Cache is already connected
// Specify unique cache key for counter
string key = "SubscriptionCounter";
// Set initial value of counter
long initialValue = 15;
// Create counter
ICounter counter = cache.DataTypeManager.CreateCounter(key, initialValue);
}
catch (OperationFailedException ex)
{
// NCache specific exception
if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// The specified key already exists in the cache,
// Either remove the existing object from the cache
// Or specify another key
}
else
{
// NCache specific exception
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
카운터 값 가져오기 및 업데이트
카운터를 만든 후 카운터 값을 업데이트할 수 있습니다. 다음 코드 샘플은 다음을 사용하여 캐시에서 카운터를 가져옵니다. GetCounter 다음을 사용하여 값을 다른 값으로 설정합니다. SetValue. 그런 다음 다음을 사용하여 값을 증가시킵니다. Increment or IncrementBy 다음을 사용하여 값을 감소시킵니다. Decrement or DecrementBy.
// Precondition: Cache is already connected
// Unique key for counter
string key = "SubscriptionCounter";
// Get counter against key
ICounter retrievedCounter = cache.DataTypeManager.GetCounter(key);
// Set value of counter to 100
retrievedCounter.SetValue(100);
// Increment value
long newValue = retrievedCounter.Increment();
// Decrement value
newValue = retrievedCounter.Decrement();
// Increment value by 10
newValue = retrievedCounter.IncrementBy(10);
// Decrement value by 5
newValue = retrievedCounter.DecrementBy(5);
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
카운터 이벤트 알림
카운터와 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트 및 데이터 구조 이벤트를 등록할 수 있습니다. 행동에 대해서는 다음을 참조하십시오. 특징적인 행동.
다음 코드 샘플은 다음의 캐시 이벤트를 등록합니다. ItemAdded ItemUpdated 이벤트를 등록할 뿐만 아니라 ItemAdded ItemUpdated 캐시의 카운터에 대한 내용입니다. 카운터를 생성하면 다음이 트리거됩니다. ItemAdded 캐시 레벨 이벤트입니다. 카운터 값이 수정되면, ItemUpdated 데이터 구조 이벤트 및 ItemUpdated 캐시 수준 이벤트가 발생합니다.
생성된 카운터에 이벤트 등록
// Precondition: Cache is already connected
// Unique cache key for counter
string key = "SubscriptionCounter";
// Set initial value of counter
long initialValue = 15;
// Create counter
ICounter counter = cache.DataTypeManager.CreateCounter(key, initialValue);
// Register ItemAdded, ItemUpdated, ItemRemoved events on counter created
// DataTypeNotificationCallback is callback method specified
counter.RegisterNotification(DataTypeDataNotificationCallback,
EventType.ItemAdded,
DataTypeEventDataFilter.Data);
// Perform operations
이벤트 알림에 대한 콜백 지정
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
if (collectionEventArgs.EventType == EventType.ItemUpdated)
{
if (collectionEventArgs.CollectionItem != null)
{
// Counter value has been updated
// Perform operations
}
}
}
카운터 잠금
카운터는 데이터 일관성을 보장하기 위해 명시적으로 잠그거나 잠금 해제할 수 있습니다. 다음 코드 샘플은 카운터를 만들고 다음을 사용하여 10초 동안 잠급니다. 로크 그런 다음 사용하여 잠금을 해제합니다. 자물쇠를 열다.
// Precondition: Cache is already connected
// Counter exists with key "SubscriptionCounter"
// Cache Key
string key = "SubscriptionCounter";
// Get counter against key
ICounter counter = cache.DataTypeManager.GetCounter(key);
// Lock counter for 10 seconds
bool isLocked = counter.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// Counter is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// Counter is not locked because either:
// Counter is not present in the cache
// Counter is already locked
}
counter.Unlock();
추가 자료
NCache 카운터 데이터 구조에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : com.alachisoft.ncache.client.데이터 구조 네임 스페이스.
Node.js : 계수기 클래스입니다.