缓存中的字典行为和使用
字典是用于存储一组对象的通用数据结构。 它也被称为 Hash、Map 和 HashMap。 它是一种无序的数据结构,提供字符串键与值的映射。 例如,可以使用字典来存储超市中所有产品的信息 产品编号 作为字典条目键。
NCache 通过提供进一步增强字典数据类型 NCache-特定功能,例如 组别, 标签, 過期, 锁定, 依赖,并且更反对它。
备注
在 Java 中,Map 对应于 .NET 中的 Dictionary。
宠物行为研究
- 字典值可以是任何原始类型或自定义对象。
- 一本词典
CacheItem
和嵌套字典尚不支持。
- 字典被命名。 因此,您需要为每个字典提供唯一的缓存键。
- 字典键只能是字符串类型。
- 不允许重复的字典键。
先决条件
- 了解与所有人员合作所需的标准先决条件 NCache 客户端功能请参阅给定页面 客户端 API 先决条件.
- 有关 API 详细信息,请参阅: 缓存, 分布式词典, 数据类型管理器, 创建字典, 身份证, 获取字典, 收藏经理, 注册通知, 数据类型数据通知回调, 事件类型, 数据类型事件数据过滤器, 锁, 开锁.
- 了解与所有人员合作所需的标准先决条件 NCache 客户端功能请参阅给定页面 客户端 API 先决条件.
- 有关 API 详细信息,请参阅: 缓存, 分布式地图, 获取数据结构管理器, 创建地图, 获取地图, 事件类型, 获取事件类型, 数据结构数据更改监听器, 数据结构改变时, 数据结构事件参数, 数据类型事件数据过滤器, 获取集合项, 锁, 开锁.
创建字典并添加数据
以下代码示例显示了如何根据缓存键在缓存中创建字典 产品字典 然后将数据添加到字典中。
Tips:
你也可以 配置可搜索属性 例如组/标签/命名标签和 失效属性 例如创建数据结构时的 Expiration/Eviction/Dependency。
// 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
示例中的实例 将数据添加到字典 并根据指定的键获取值。
// 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上.
参见
.NET: Alachisoft.NCache.Client.DataTypes 命名空间。
Java的: COM。alachisoft.ncache.client.数据结构 命名空间。
Python: ncache.client.数据结构 类。