• Facebook
  • Twitter
  • Youtube
  • Allineato
  • RSS
  • Docs
  • Confronti
  • Blog
  • Scaricare
  • Contattaci
Scaricare
Mostra/Nascondi sommario

Comportamento e utilizzo del dizionario nella cache

NCache Il Dizionario Distribuito è una struttura dati distribuita e non ordinata per l'archiviazione di coppie chiave-valore in un cluster. È ideale per ricerche rapide basate su chiavi. Supporta eventi a livello di cache e di elemento. NCache migliora ulteriormente il tipo di dati del dizionario fornendo NCache-funzioni specifiche come Gruppi, Tags, Scadenza, Blocco, dipendenzeE altro ancora.

Chiamato anche Hash, Map o HashMap, un NCache Il dizionario è una struttura dati generica per la memorizzazione di un gruppo di oggetti. Associa le chiavi stringa ai valori. Ad esempio, un dizionario può essere utilizzato per memorizzare le informazioni di tutti i prodotti in un supermercato in base ai loro numero identificativo del prodotto come chiave di immissione del dizionario.

Note:

In Java, una mappa corrisponde a un dizionario in .NET.

NCache Comportamento del dizionario distribuito

  • Un valore del dizionario può essere di qualsiasi tipo primitivo o oggetto personalizzato.
  • Un dizionario di CacheItem e i dizionari annidati non sono ancora supportati.
  • I dizionari sono nominati. Pertanto, è necessario fornire una chiave cache univoca per ciascun dizionario.
  • Una chiave del dizionario può essere solo di tipo stringa.
  • Non sono consentite chiavi del dizionario duplicate.

Prerequisiti

Prima di usare il NCache Per le API lato client, assicurarsi che siano soddisfatti i seguenti prerequisiti:

  • .NET
  • Java
  • Installa i seguenti pacchetti NuGet nella tua applicazione client .NET:
    • Impresa: Alachisoft.NCache.Sdk
    • Open Source: Alachisoft.NCache.SDK open source
  • Includere i seguenti spazi dei nomi nell'applicazione:
    • Alachisoft.NCache.Cliente
    • Alachisoft.NCache.Eccezioni.di.runtime
    • Alachisoft.NCache.Tipi.dati.client
    • Alachisoft.NCache.Client.DataTypes.Collections
    • Alachisoft.NCache.Memorizzazione.della.cache
    • Alachisoft.NCache.Eventi.di.runtime
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: ICache, Dizionario distribuito, IdataTypeManager, Crea dizionario, OttieniDizionario, ICollection Manager, Notifica di registrazione, DataTypeDataNotificationRichiamata, Tipo di evento, DataTypeEventDataFilter, bloccare, Sbloccare, DataType Manager, Ottieni, inserire, Rimuovere, DataTypeEventArg.
  • Aggiungi le seguenti dipendenze Maven per la tua applicazione client Java in pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise-->
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Importa i seguenti pacchetti nell'applicazione client Java:
    • importare com.alachisoft.ncache.client.*;
    • importare com.alachisoft.ncache.runtime.eccezione.*;
    • importare com.alachisoft.ncache.client.datastructures.*;
    • importare com.alachisoft.ncache.runtime.events.*;
    • importare com.alachisoft.ncache.runtime.dependencies.*;
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, Mappa distribuita, getDataStructuresManager, createMap, getMap, Tipo di evento, getEventType, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, DataTypeEventDataFilter, getCollectionItem, bloccare, sbloccare, ottenere, insert, rimuovere, addChangeListener.

Come creare un dizionario e aggiungere dati

L'esempio di codice seguente mostra come viene creato un dizionario nella cache rispetto alla chiave della cache Dizionario del prodottoe quindi i dati vengono aggiunti al dizionario.

Consiglio

Puoi anche configurare gli attributi ricercabili come Gruppi/Tag/Tag con nome e attributi di invalidamento come scadenza/eliminazione/dipendenza durante la creazione di una struttura dati.

  • .NET
  • Java
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 
}
try
{
  // 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);
  }
}
catch (OperationFailedException ex) 
{
    if (ex.getErrorCode() == 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.getErrorCode() == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES) {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    } else {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
} 
catch (Exception ex) 
{
    // Any generic exception like IllegalArgumentException or NullPointerException
}
Note:

Per garantire che l'operazione sia a prova di errore, si consiglia di gestire eventuali potenziali eccezioni all'interno dell'applicazione, come spiegato in Gestione dei guasti.

Come recuperare il dizionario dalla cache

Puoi recuperare un dizionario dalla cache che accetta una chiave della cache come parametro. Questa chiave è il nome del dizionario, specificato durante la creazione del dizionario.

Avvertenza

Se l'elemento recuperato non è di tipo dizionario, a Type mismatch viene generata un'eccezione.

  • .NET
  • Java
// 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
}
// 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
}

Come recuperare i valori delle chiavi specifiche del dizionario

È possibile recuperare i valori per voci specifiche del dizionario utilizzando Get. L'esempio di codice seguente usa il dictionary istanza dall'esempio per aggiunta di dati al dizionario e ottiene valori rispetto alle chiavi specificate.

Note:

Se non esiste alcun valore rispetto alla chiave specificata, viene restituito null.

  • .NET
  • Java
// 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
}
// 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
}

Come inserire dati in un dizionario esistente

È possibile inserire dati in un dizionario esistente utilizzando Insert. L'esempio di codice seguente recupera i nuovi prodotti dall'origine dati e li inserisce in un dizionario già esistente nella cache.

Note:

Se le chiavi esistono già, questo sovrascriverà i valori nel dizionario.

  • .NET
  • Java
// 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);
// 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);

Come rimuovere elementi dal dizionario

Note:

Se la chiave specificata da rimuovere non esiste, non viene restituito nulla. È possibile verificare il numero di chiavi restituite utilizzando il tipo di restituzione di Remove.

È possibile rimuovere elementi da un dizionario per una data raccolta di chiavi. Il seguente esempio di codice rimuove le voci del dizionario per i prodotti scaduti utilizzando Remove.

Consiglio

Per rimuovere l'intero dizionario dalla cache, fare riferimento al file Rimuovere le strutture di dati dalla cache .

  • .NET
  • Java
// 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);
// 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);

Registrazione delle notifiche degli eventi sul dizionario

È possibile registrare eventi cache, eventi basati su chiave ed eventi struttura dati su una struttura dati come un dizionario. Per il comportamento fare riferimento a comportamento in termini di funzionalità.

I seguenti esempi di codice registrano ItemAdded, ItemUpdatede ItemRemoved eventi della struttura dati sul dizionario. La creazione di un dizionario attiva un ItemAdded evento a livello di cache. L'aggiunta di un elemento a un dizionario esistente attiva un ItemAdded evento della struttura dati e un ItemUpdated Evento a livello di cache.

Come registrare eventi su un dizionario creato

  • .NET
  • Java
// 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
// 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 Map created
map.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations

Come specificare il callback per la notifica degli eventi

  • .NET
  • Java
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;
        }
    }
};

Come bloccare un dizionario

Il dizionario può essere bloccato e sbloccato esplicitamente per garantire la coerenza dei dati. L'esempio di codice seguente crea un dizionario e lo blocca per un periodo di 10 secondi utilizzando bloccare e poi lo sblocca usando Sbloccare.

  • .NET
  • Java
// 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();
// Precondition: 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();

Risorse addizionali

NCache fornisce un'applicazione di esempio per la struttura dei dati del dizionario GitHub.

Vedere anche

.NETTO: Alachisoft.NCache.Tipi.dati.client spazio dei nomi.
Giava: com.alachisoft.ncache.client.datastructures spazio dei nomi.

Contattaci

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
E-MAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Confronto edizione
  • NCache Architettura
  • Parametri di riferimento
Scaricare
Prezzi
Prova Parco giochi

Distribuzioni
  • Cloud (SaaS e software)
  • On-Locale
  • kubernetes
  • docker
Casi d'uso tecnici
  • Sessioni ASP.NET
  • Sessioni ASP.NET Core
  • Messaggistica Pub/Sub
  • SignalR in tempo reale per ASP.NET
  • Internet of Things (IoT)
  • Database NoSQL
  • Streaming Processing
  • Microservices
Risorse
  • Articoli di riviste
  • Articoli di terze parti
  • Articoli
  • Video
  • Fogli bianchi
  • Spettacoli
  • trattativa
  • Blog
  • Docs
Casi di studio dei clienti
  • Testimonianze
  • Clienti
Assistenza
  • Pianificare un demo
  • Forum (Google Gruppi)
  • Consigli
Azienda
  • Leadership
  • Partner
  • News
  • Eventi
  • Lavora con noi
Contattaci

  • IngleseCinese (semplificato)FranceseTedescoItalianoGiapponeseCoreanoPortogheseCorsi

  • Contattaci
  •  
  • Mappa del sito
  •  
  • Termini d’uso
  •  
  • Informativa privacy
© Copyright Alachisoft 2002 - . Tutti i diritti riservati. NCache è un marchio registrato di Diyatech Corp.
Torna in alto