캐시의 사전 동작 및 사용
사전은 개체 그룹을 저장하기 위한 범용 데이터 구조입니다. Hash, Map, HashMap이라고도 합니다. 값에 대한 문자열 키 매핑을 제공하는 정렬되지 않은 데이터 구조입니다. 예를 들어, 사전을 사용하여 슈퍼마켓에 있는 모든 제품의 정보를 해당 제품과 비교하여 저장할 수 있습니다. 제품 ID 사전 입력 키로.
NCache 제공하여 사전 데이터 유형을 더욱 향상시킵니다. NCache-다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성, 그리고 그것에 반대합니다.
주의 사항
Java에서 맵은 .NET의 사전에 해당합니다.
행동
- 사전 값은 모든 기본 유형 또는 사용자 정의 개체일 수 있습니다.
- 의 사전
CacheItem
중첩된 사전은 아직 지원되지 않습니다.
- 사전이 명명됩니다. 따라서 각 사전에 대해 고유한 캐시 키를 제공해야 합니다.
- 사전 키는 문자열 유형만 될 수 있습니다.
- 중복 사전 키는 허용되지 않습니다.
사전 조건
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트측 기능은 다음 페이지를 참조하세요. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 아이캐시, IDistributedDictionary, IDataTypeManager, 사전 만들기, 사전, 사전 가져오기, ICollectionManager, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다.
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 클라이언트측 기능은 다음 페이지를 참조하세요. 클라이언트 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 캐시, 분산 맵, getDataStructuresManager, 지도 만들기, 지도를 얻다, 이벤트 유형, 이벤트 유형, DataStructureDataChangeListener, onDataStructure변경됨, DataStructureEventArg, 데이터 유형 이벤트 데이터 필터, getCollection항목, 자물쇠, 잠금을 해제.
사전 생성 및 데이터 추가
다음 코드 샘플은 캐시 키에 대해 캐시에서 사전을 만드는 방법을 보여줍니다. 제품사전 그런 다음 데이터가 사전에 추가됩니다.
// 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);
}
// Precondition: Cache must be connected
// Specify unique cache key for map
String key = "ProductMap";
// Create Map of Product type
DistributedMap<String, Product> map = cache.getDataStructuresManager().createMap(key, Product.class);
// Adding products to map
Product[] products = fetchProducts();
for (var product : products) {
// Add products
String productKey = "Product:" + product.getProductID();
map.put(productKey, product);
}
# Precondition: Cache must be connected
# Specify unique cache key for dictionary
key = "ProductDictionary"
# Create dictionary of Product type
dictionary = cache.get_data_structures_manager().create_dictionary(key, Product)
# Adding products to dictionary
products = fetch_products()
for product in products:
# Add products
product_key = "Product:" + product.get_product_id()
dictionary.put(product_key, product)
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
캐시에서 사전 가져오기
캐시 키를 매개변수로 사용하는 캐시에서 사전을 가져올 수 있습니다. 이 키는 사전 생성 중에 지정되는 사전의 이름입니다.
경고
가져오는 항목이 사전 유형이 아닌 경우 Type mismatch
예외가 발생합니다.
// Dictionary with this key already exists in cache
string key = "ProductDictionary";
// Get dictionary and show items of dictionary
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
}
// Precondition: Cache is already connected
// Map with this key already exists in cache
String key = "ProductMap";
// Get map and show items of map
DistributedMap<String, Product> retrievedMap = cache.getDataStructuresManager().getMap(key, Product.class);
if (retrievedMap != null) {
for (var item : retrievedMap) {
// Perform operations
}
} else {
// Map does not exist
}
# Precondition: Cache is already connected
# Dictionary with this key already exists in cache
key = "ProductDictionary"
# Get dictionary and show items of dictionary
retrieved_dictionary = cache.get_data_structures_manager().get_dictionary(key, Product)
if retrieved_dictionary is not None:
for item in retrieved_dictionary.get_iterator():
# Perform operations
print(item)
else:
# Dictionary does not exist
print("Dictionary not found")
특정 사전 키의 값 가져오기
다음을 사용하여 사전 항목의 값만 가져올 수 있습니다. Get
. 다음 코드 샘플에서는 dictionary
에 대한 예의 인스턴스 사전에 데이터 추가 지정된 키에 대해 값을 가져옵니다.
주의 사항
지정된 키에 대해 값이 없으면 null이 반환됩니다.
// 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
}
// Precondition: Cache is already connected
// Map exists in cache
// Create list of keys to fetch corresponding values
var keys = new ArrayList<String>();
keys.add("Product:1001");
keys.add("Product:1002");
keys.add("Product:1003");
// Get values against keys
// "map" instance was created while creating map
Collection<Product> values = map.get(keys);
for (var value : values) {
// Perform operations
}
# Precondition: Cache is already connected
# Dictionary exists in cache
# Create list of keys to fetch corresponding values
keys = [
"Product:1001",
"Product:1002",
"Product:1003"
]
# Get values against keys
# "dictionary" instance was created while creating dictionary
values = dictionary.get(keys)
for value in values:
# Perform operations
print(value)
기존 사전에 데이터 삽입
다음을 사용하여 기존 사전에 데이터를 삽입할 수 있습니다. Insert
. 다음 코드 샘플은 데이터 소스에서 새 제품을 가져와 캐시 내에 이미 있는 사전에 삽입합니다.
주의 사항
키가 이미 존재하는 경우 사전의 값을 덮어씁니다.
// 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);
// Precondition: Cache is already connected
// Map with this key already exists in cache
String key = "ProductMap";
// Get map to insert more values
DistributedMap<String, Product> retrievedMap = cache.getDataStructuresManager().getMap(key, Product.class);
// Create map of new products to be added
DistributedMap<String, Product> newProducts = cache.getDataStructuresManager().getMap(key, Product.class);
Product[] products = fetchProducts();
for (var product : products) {
// Add new products
String productKey = "Product:" + product.getProductID();
newProducts.put(productKey, product);
}
// Append map entries to existing map
retrievedMap.insert(newProducts);
# Pre-condition: Cache is already connected
# Dictionary with this key already exists in cache
key = "ProductDictionary"
# Get dictionary to insert more values
retrieved_dictionary = cache.get_data_structures_manager().get_dictionary(key, Product)
# Create dictionary of new products to be added
new_products = {}
products = fetch_products()
for product in products:
# Add new products
product_key = "Product:" + product.get_product_id()
new_products[product_key] = product
# Append dictionary entries to existing dictionary
retrieved_dictionary.insert(new_products)
# You can verify using len(retrieved_dictionary)
사전에서 항목 제거
주의 사항
제거하도록 지정된 키가 존재하지 않으면 아무 것도 반환되지 않습니다. 반환 유형을 사용하여 반환된 키 수를 확인할 수 있습니다. Remove
.
주어진 키 컬렉션에 대해 사전에서 항목을 제거할 수 있습니다. 다음 코드 샘플은 다음을 사용하여 만료된 제품에 대한 사전 엔터티를 제거합니다. Remove
.
// Dictionary with this key already exists in cache
string key = "ProductDictionary";
// Get dictionary and show items of dictionary
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);
// Precondition: Cache is already connected
// Map with this key already exists in cache
String key = "ProductMap";
// Get map and show items of map
DistributedMap<String, Product> retrievedMap = cache.getDataStructuresManager().getMap(key, Product.class);
// Create list of keys to remove
List<String> keysToRemove = fetchExpiredProducts();
// Number of keys removed is returned
int itemsRemoved = retrievedMap.remove(keysToRemove);
# Precondition: Cache is already connected
# Dictionary with this key already exists in cache
key = "ProductDictionary"
# Get dictionary and show items of dictionary
retrieved_dictionary = cache.get_data_structures_manager().get_dictionary(key, Product)
# Create list of keys to remove
keys_to_remove = fetch_expired_products_ids()
# Number of keys removed is returned
items_removed = retrieved_dictionary.remove(keys_to_remove)
사전 이벤트 알림
사전과 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트, 데이터 구조 이벤트를 등록할 수 있습니다. 행동에 대해서는 다음을 참조하세요. 특징적인 행동.
다음 코드 샘플은 다음의 캐시 이벤트를 등록합니다. ItemAdded
및 ItemUpdated
이벤트를 등록할 뿐만 아니라 ItemAdded
및 ItemUpdated
캐시의 사전에 있습니다. 캐시에 사전이 생성되면 ItemAdded
캐시 수준 이벤트가 시작됩니다. 그러나 항목이 사전에 추가되면 ItemAdded
데이터 구조 이벤트가 발생하고 ItemUpdated
캐시 레벨 이벤트가 발생합니다.
생성된 사전에 이벤트 등록
// Unique cache key for dictionary
string key = "ProductDictionary";
// Create 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
// Precondition: Cache is already connected
// Unique cache key for map
String key = "ProductMap";
// Create map of type Product
DistributedMap<String, Product> map = cache.getDataStructuresManager().createMap(key, Product.class);
// Create EnumSet of event types
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
EventType.ItemUpdated, EventType.ItemRemoved);
// Register ItemAdded, ItemUpdated, ItemRemoved events on queue created
// dataChangeListener is the specified callback method
DataStructureDataChangeListener dataChangeListener = dataStructureListener.onDataStructureChanged(collectionName, args);
map.addChangeListener(dataChangeListener, enumSet, DataTypeEventDataFilter.Data);
// Perform operations
def datastructure_callback_function(collection_name, collection_event_args):
# Perform Operations
print("Event Fired for " + str(collection_name))
# Precondition: Cache is already connected
# Unique cache key for dictionary
key = "ProductDictionary"
# Create dictionary
product_dictionary = cache.get_data_structures_manager().create_hashset(key, int)
# Register ItemAdded, ItemUpdated, ItemRemoved events on hashset created
events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]
product_dictionary.add_change_listener(datastructure_callback_function, events_list, ncache.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;
}
}
DataStructureDataChangeListener dataStructureListener = new DataStructureDataChangeListener() {
@Override
public void onDataStructureChanged(String collection, DataStructureEventArg dataStructureEventArg) {
switch (dataStructureEventArg.getEventType()) {
case ItemAdded:
// Item has been added to the collection
break;
case ItemUpdated:
if (dataStructureEventArg.getCollectionItem() != null) {
//Item has been updated in the collection
// perform operations
}
break;
case ItemRemoved:
//Item has been removed from the collection
break;
}
}
};
def datastructure_callback_function(collection_name: str, collection_event_args: DataStructureEventArg):
if collection_event_args.get_event_type() is ncache.EventType.ITEM_ADDED:
# Item has been added to the collection
print("Item added in " + collection_name)
elif collection_event_args.get_event_type() is ncache.EventType.ITEM_UPDATED:
# Item has been updated in the collection
print("Item updated in " + collection_name)
elif collection_event_args.get_event_type() is ncache.EventType.ITEM_REMOVED:
# Item has been removed from the collection
print("Item removed from " + collection_name)
사전 잠금
데이터 일관성을 보장하기 위해 사전을 명시적으로 잠그거나 잠금 해제할 수 있습니다. 다음 코드 샘플은 사전을 생성하고 다음을 사용하여 10초 동안 잠급니다. 로크 그런 다음 사용하여 잠금을 해제합니다. 자물쇠를 열다.
// 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();
// Preconditions: Cache is already connected
// Map exists with key "ProductMap"
// Cache Key
String key = "ProductMap";
// Get dictionary
DistributedMap<String, Product> map = cache.getDataStructuresManager().getMap(key, Product.class);
// Lock map for 10 seconds
boolean isLocked = map.lock(TimeSpan.FromSeconds(10));
if (isLocked) {
// Map is successfully locked for 10 seconds
// Unless explicitly unlocked
} else {
// Map is not locked because either:
// Map is not present in the cache
// Map is already locked
}
map.unlock();
추가 자료
NCache 사전 데이터 구조에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : COM.alachisoft.ncache.client.데이터구조 네임 스페이스.
파이썬 : ncache.client.데이터구조 클래스입니다.