キャッシュ内の辞書の動作と使用法
辞書は、オブジェクトのグループを格納するための汎用データ構造です。 ハッシュ、マップ、ハッシュマップとも呼ばれます。 これは順序付けされていないデータ構造であり、値に対する文字列キーのマッピングを提供します。 たとえば、辞書を使用して、スーパーストア内のすべての製品の情報を、その製品の情報と照らし合わせて保存できます。 製品番号 辞書のエントリキーとして。
NCache を提供することにより、辞書データ型をさらに強化します。 NCache- などの特有の機能 グループ, タグ, 満了, ロッキング, 依存関係、さらにそれに反対します。
Note
Java では、マップは .NET のディクショナリに対応します。
行動
- ディクショナリ値は、任意のプリミティブ型またはカスタムオブジェクトにすることができます。
- の辞書
CacheItem
ネストされた辞書はまだサポートされていません。
- 辞書には名前が付けられています。 したがって、辞書ごとに一意のキャッシュ キーを提供する必要があります。
- 辞書キーは文字列型のみにすることができます。
- 重複する辞書キーは許可されていません。
前提条件
- すべてを使用するために必要な標準的な前提条件について学習するには NCache クライアント側の機能については、次のページを参照してください。 クライアント側 API の前提条件.
- APIの詳細については、以下を参照してください。 Iキャッシュ, IDistributedDictionary, IDataTypeManager, 辞書の作成, I辞書, GetDictionary, Iコレクションマネージャー, 登録通知, DataTypeDataNotificationCallback, イベントタイプ, データタイプイベントデータフィルター, ロック, アンロック.
- すべてを使用するために必要な標準的な前提条件について学習するには NCache クライアント側の機能については、次のページを参照してください。 クライアント側 API の前提条件.
- APIの詳細については、以下を参照してください。 キャッシュ, 分散マップ, getDataStructuresManager, マップの作成, マップを取得する, イベントタイプ, getEventType, DataStructureDataChangeListener, onDataStructureChanged, データ構造イベント引数, データタイプイベントデータフィルター, getCollectionItem, ロック, アンロック.
辞書を作成してデータを追加する
次のコード サンプルは、キャッシュ キーに対してキャッシュ内にディクショナリを作成する方法を示しています。 製品辞書 そしてデータが辞書に追加されます。
先端
また、ワイルドカード*を使用すると、任意の文字にマッチし、XNUMXつのコマンドで複数のファイルを削除することができます。 検索可能な属性を構成する グループ/タグ/名前付きタグなど 無効化属性 データ構造の作成中の有効期限/削除/依存関係など。
// 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)
Note
操作がフェイルセーフであることを保証するために、で説明されているように、アプリケーション内の潜在的な例外を処理することをお勧めします。 失敗の処理.
キャッシュから辞書を取得する
キャッシュキーをパラメーターとして受け取るキャッシュから辞書を取得できます。 このキーは、ディクショナリの作成時に指定されたディクショナリの名前です。
警告
フェッチされるアイテムがディクショナリ タイプでない場合、 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
の例からのインスタンス 辞書にデータを追加する 指定されたキーに対する値を取得します。
Note
指定されたキーに対して値が存在しない場合、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
。 次のコード サンプルは、データ ソースから新しい製品をフェッチし、キャッシュ内にすでに存在するディクショナリにそれらを挿入します。
Note
キーが既に存在する場合、辞書内の値が上書きされます。
// 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)
辞書からアイテムを削除する
Note
削除するように指定されたキーが存在しない場合は、何も返されません。 返されたキーの数は、戻り値の型を使用して確認できます。 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.Client.DataTypes 名前空間
Java: comの。alachisoft.ncache.client.datastructs 名前空間
Python: ncache.client.datastructs とに提供されます。