캐시의 사전 동작 및 사용
NCache 분산 사전(Distributed Dictionary)은 클러스터 전체에 걸쳐 키-값 쌍을 저장하는 분산형 비정렬 데이터 구조입니다. 빠른 키 기반 조회에 이상적이며, 캐시 및 항목 수준 이벤트를 지원합니다. NCache 제공하여 사전 데이터 유형을 더욱 향상시킵니다. NCache-다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성수록.
해시, 맵 또는 해시맵이라고도 불리는 것은 NCache 딕셔너리는 객체 그룹을 저장하는 데 사용되는 범용 데이터 구조입니다. 문자열 키를 값에 매핑합니다. 예를 들어, 딕셔너리는 대형 매장의 모든 제품 정보를 해당 키와 값에 대해 저장하는 데 사용할 수 있습니다. 제품 ID 사전 입력 키로.
주의 사항
Java에서 맵은 .NET의 사전에 해당합니다.
NCache 분산 사전 동작
- 사전 값은 모든 기본 유형 또는 사용자 정의 개체일 수 있습니다.
- 의 사전
CacheItem중첩 딕셔너리는 아직 지원되지 않습니다. - 사전이 명명됩니다. 따라서 각 사전에 대해 고유한 캐시 키를 제공해야 합니다.
- 사전 키는 문자열 유형만 될 수 있습니다.
- 중복 사전 키는 허용되지 않습니다.
사전 조건
사용하기 전에 NCache 클라이언트 측 API를 사용할 때 다음 전제 조건을 충족하는지 확인하십시오.
- .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
- 기업: Alachisoft.NCache.SDK
- 오픈 소스: Alachisoft.NCache오픈소스 SDK
- 애플리케이션에 다음 네임스페이스를 포함합니다.
- 캐시가 실행 중이어야 합니다.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 아이캐시, IDistributedDictionary, IDataTypeManager, 사전 만들기, 사전 가져오기, ICollectionManager, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다, 데이터 유형 관리자, 돈을 받아가세요, 끼워 넣다, 제거, 데이터 유형 이벤트 인수.
사전을 만들고 데이터를 추가하는 방법
다음 코드 샘플은 캐시 키에 대해 캐시에서 사전을 만드는 방법을 보여줍니다. 제품사전그런 다음 데이터가 사전에 추가됩니다.
팁
당신은 또한 수 검색 가능한 속성 구성 그룹/태그/명명된 태그와 같은 무효화 속성 데이터 구조를 생성하는 동안 만료/퇴거/종속성과 같은.
try
{
// Precondition: Cache must be connected
// Specify unique cache key for dictionary
string key = "ProductDictionary";
// Create dictionary of Product type
IDistributedDictionary<string, Product> dictionary = cache.DataTypeManager.CreateDictionary<string, Product>(key);
// Adding products to dictionary
Product[] products = FetchProducts();
foreach(var product in products)
{
// Add products
string productKey = $"Product:{product.ProductID}";
dictionary.Add(productKey, product);
}
}
catch (OperationFailedException ex)
{
// NCache specific exception
if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// The specified key already exists in cache,
// Either remove the existing object from cache
// Or specify another key
}
else if (ex.ErrorCode == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES)
{
// Data structures cannot be of CacheItem type
// CacheItems cannot be added in data structures
}
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
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
캐시에서 사전을 가져오는 방법
캐시 키를 매개변수로 사용하는 캐시에서 사전을 가져올 수 있습니다. 이 키는 사전 생성 중에 지정되는 사전의 이름입니다.
경고
가져오는 항목이 사전 유형이 아닌 경우 Type mismatch 예외가 발생합니다.
// Precondition: Cache is already connected
// Dictionary with this key already exists in cache
string key = "ProductDictionary";
// Get the dictionary and iterate through its items
IDistributedDictionary<string, Product> retrievedDictionary = cache.DataTypeManager.GetDictionary<string, Product>(key);
if (retrievedDictionary != null)
{
foreach (var item in retrievedDictionary)
{
// Perform operations
}
}
else
{
// Dictionary does not exist
}
특정 딕셔너리 키의 값을 가져오는 방법
특정 사전 항목의 값을 검색하려면 다음을 사용하세요. Get. 다음 코드 샘플에서는 dictionary 에 대한 예의 인스턴스 사전에 데이터 추가 지정된 키에 대해 값을 가져옵니다.
주의 사항
지정된 키에 대해 값이 없으면 null이 반환됩니다.
// Precondition: Cache is already connected
// Dictionary exists in cache
// Create list of keys to fetch corresponding values
var keys = new List<string>();
keys.Add("Product:1001");
keys.Add("Product:1002");
keys.Add("Product:1003");
// Get values against keys
// "dictionary" instance was created while creating dictionary
ICollection<Product> values = dictionary.Get(keys);
foreach (var value in values)
{
// Perform operations
}
기존 딕셔너리에 데이터를 삽입하는 방법
다음을 사용하여 기존 사전에 데이터를 삽입할 수 있습니다. Insert. 다음 코드 샘플은 데이터 소스에서 새 제품을 가져와 캐시 내에 이미 있는 사전에 삽입합니다.
주의 사항
키가 이미 존재하는 경우 사전의 값을 덮어씁니다.
// Precondition: Cache is already connected
// Dictionary with this key already exists in cache
string key = "ProductDictionary";
// Get dictionary to insert more values
IDistributedDictionary<string, Product> retrievedDictionary = cache.DataTypeManager.GetDictionary<string, Product>(key);
// Create dictionary of new products to be added
IDictionary<string, Product> newProducts = new Dictionary<string, Product>();
Product[] products = FetchProducts();
foreach (var product in products)
{
// Add new products
string productKey = $"Product:{product.ProductID}";
newProducts.Add(productKey, product);
}
// Append dictionary entries to existing dictionary
retrievedDictionary.Insert(newProducts);
사전에서 항목을 제거하는 방법
주의 사항
제거하도록 지정된 키가 존재하지 않으면 아무 것도 반환되지 않습니다. 반환 유형을 사용하여 반환된 키 수를 확인할 수 있습니다. Remove.
주어진 키 모음에 대해 딕셔너리에서 항목을 제거할 수 있습니다. 다음 코드 예제는 만료된 제품에 대한 딕셔너리 항목을 제거합니다. Remove.
팁
캐시에서 전체 사전을 제거하려면 다음을 참조하세요. 캐시에서 데이터 구조 제거 페이지를 확인하시기 바랍니다.
// Precondition: Cache is already connected
// Dictionary with this key already exists in cache
string key = "ProductDictionary";
// Get the dictionary and iterate through its items
IDistributedDictionary<string, Product> retrievedDictionary = cache.DataTypeManager.GetDictionary<string, Product>(key);
// Create list of keys to remove
List<string> keysToRemove = FetchExpiredProducts();
// Number of keys removed is returned
int itemsRemoved = retrievedDictionary.Remove(keysToRemove);
딕셔너리에 이벤트 알림 등록하기
사전과 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트, 데이터 구조 이벤트를 등록할 수 있습니다. 행동에 대해서는 다음을 참조하세요. 기능별 동작.
다음 코드 샘플은 레지스터를 등록합니다. ItemAdded, ItemUpdated예산 및 ItemRemoved 사전의 데이터 구조 관련 이벤트. 사전을 생성하면 이벤트가 발생합니다. ItemAdded 캐시 레벨 이벤트입니다. 기존 사전에 항목을 추가하면 이 이벤트가 발생합니다. ItemAdded 데이터 구조 이벤트 및 ItemUpdated 캐시 레벨 이벤트.
생성된 딕셔너리에 이벤트를 등록하는 방법
// Precondition: Cache is already connected
// Unique cache key for dictionary
string key = "ProductDictionary";
// Create a dictionary of Product type
IDistributedDictionary<string, Product> dictionary = cache.DataTypeManager.CreateDictionary<string, Product>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on dictionary created
// DataTypeNotificationCallback is callback method specified
dictionary.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
DataTypeEventDataFilter.Data);
// Perform operations
이벤트 알림에 대한 콜백 함수 지정 방법
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
switch (collectionEventArgs.EventType)
{
case EventType.ItemAdded:
// Item has been added to the collection
break;
case EventType.ItemUpdated:
if (collectionEventArgs.CollectionItem != null)
{
// Item has been updated in the collection
// Perform operations
}
break;
case EventType.ItemRemoved:
// Item has been removed from the collection
break;
}
}
사전을 잠그는 방법
데이터 일관성을 보장하기 위해 사전을 명시적으로 잠그거나 잠금 해제할 수 있습니다. 다음 코드 샘플은 사전을 생성하고 다음을 사용하여 10초 동안 잠급니다. 로크 그런 다음 사용하여 잠금을 해제합니다. 자물쇠를 열다.
// Precondition: Cache is already connected
// Dictionary exists with key "ProductDictionary"
// Cache Key
string key = "ProductDictionary";
// Get dictionary
IDistributedDictionary<string, Product> dictionary = cache.DataTypeManager.GetDictionary<string, Product>(key);
// Lock dictionary for 10 seconds
bool isLocked = dictionary.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// Dictionary is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// Dictionary is not locked because either:
// Dictionary is not present in the cache
// Dictionary is already locked
}
dictionary.Unlock();
추가 자료
NCache 사전 데이터 구조에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : com.alachisoft.ncache.client.데이터 구조 네임 스페이스.