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

Elenca il comportamento e l'utilizzo nella cache

Una lista distribuita è una struttura dati ordinata in cui è possibile aggiungere o rimuovere dati. Ad esempio, le liste gestiscono i prodotti aggiunti al carrello di un sito web di e-commerce. Supponiamo che un utente aggiunga al carrello prodotti come Ombrello, Mele Verdi e Caffè. Prima di completare la transazione, il prodotto Mele Verdi viene rimosso e sostituito con un nuovo prodotto Pere. Questo è possibile perché la lista può essere aggiornata in qualsiasi punto, senza influire sulle prestazioni.

NCache migliora ulteriormente la struttura dei dati dell'elenco fornendo NCache-funzioni specifiche come Gruppi, Tags, Scadenza, Blocco, dipendenzee altro ancora. In questo scenario, l'azienda desidera che l'elenco del carrello venga mantenuto solo finché la sessione è attiva. Pertanto, è possibile associare una scadenza a ciascun elenco creato, pari al valore di timeout della sessione.

NCache Comportamento e limitazioni dell'elenco

Dal NCache Gli elenchi sono progettati per il ridimensionamento dinamico: grandi set di dati possono essere archiviati in uno spazio di memoria distribuito, pur mantenendo un rapido accesso basato sull'indice.

  • Un elenco può essere di qualsiasi tipo primitivo o oggetto personalizzato.
  • Un elenco di CacheItem e le liste annidate non sono ancora supportate.
  • Gli elenchi sono accessibili direttamente dall'indice.
  • Gli elenchi hanno un nome. Pertanto, è necessario fornire una chiave di cache univoca per ogni elenco.
  • I valori nulli non sono supportati.
  • Sono supportati valori duplicati.

Prerequisiti

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

  • .NET
  • Java
  • Node.js
  • 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, IDdistributedList, IdataTypeManager, Crea lista, Aggiungi intervallo, Inserisci in testa, OttieniLista, Rimuovi intervallo, Notifica di registrazione, DataTypeDataNotificationRichiamata, Tipo di evento, DataTypeEventDataFilter, bloccare, Sbloccare, DataType Manager, 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, Elenco distribuito, getDataStructuresManager, creareLista, aggiungiRange, rimuoviRange, inserisci in testa, getList, DataStructureDataChangeListener, onDataStructureChanged, addChangeListener, Tipo di evento, getEventType, DataTypeEventDataFilter, DataStructureEventArg, getCollectionItem, bloccare, sbloccare.
  • Installa e includi il seguente modulo nella tua applicazione client Node.js:

    • Impresa: client ncache
  • Includi la seguente classe nella tua applicazione:

    • Cache
    • Gestore struttura dati
    • Elenco distribuito
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, Elenco distribuito, getDataStructuresManager, creareLista, aggiungiRange, getList, inserisci in testa, rimuovere, rimuoviRangeCollection, DataStructureDataChangeListener, Tipo di evento, addChangeListener, DataTypeEventDataFilter , DataStructureEventArg, getEventType, getCollectionItem.

Come creare un elenco distribuito e aggiungere dati

CreateList consente alle applicazioni di creare una raccolta distribuita dedicata che supporta criteri di invalidazione automatica dei dati, come Scadenza o Espulsione.

L'esempio di codice seguente mostra come un elenco di Prodotto i tipi possono essere creati nella cache utilizzando CreateList contro la chiave della cache Elenco prodotti. I prodotti vengono aggiunti all'elenco utilizzando Add, quindi una nuova gamma di prodotti viene aggiunta all'elenco utilizzando AddRange.

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
  • Node.js
try
{
  // Precondition: Cache is already connected

  // Specify unique cache key for list
  string key = "ProductList";

  // Create list of Product type
  IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);

  // Get products to add to list
  Product[] products = FetchProducts();

  foreach (var product in products)
  {
      // Add products to list
      list.Add(product);
  }

  // Get new products
  Product[] newProducts = FetchNewProducts();

  // Append list of new Products to existing list
  list.AddRange(newProducts);
}
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
    {
        // 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 is already connected

  // Specify unique cache key for list
  String key = "ProductList";

  // Create list of Product type
  DistributedList<Product> list = cache.getDataStructuresManager().createList(key, Product.class);

  // Get products to add to list
  Product[] products = FetchProducts();

  for (var product : products) 
  {
      // Add products to list
      list.add(product);
  }

  // Get new products
  Product[] newProducts = FetchNewProducts();

  // Append list of new Products to existing list
  list.addRange(Arrays.asList(newProducts));
}
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
}
try
{
  // This is an async method
  // Precondition: Cache is already connected

  // Specify unique cache key for list
  var key = "ProductList";

  // Create list
  var manager = await this.cache.getDataStructuresManager();
  var list = await manager.createList(key, ncache.JsonDataType.Object);

  // Get products to add to list
  var products = this.fetchProducts();

  for (var product of products) {
  // Add products to list
  list.add(product);
  }

  // Get new products
  var newProducts = this.fetchNewProducts();

  // Append list of new Products to existing list
  list.addRange(newProducts);
}
catch (error) {
  // Handle errors
}
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 aggiornare gli elementi in un elenco distribuito

È possibile aggiornare gli elenchi e i relativi elementi utilizzando gli indici, poiché è possibile accedere agli elenchi tramite indice. Il seguente esempio di codice aggiorna un valore in un elenco esistente (creato nell'esempio precedente) utilizzando l'indice. Quindi recupera un articolo in vendita e lo aggiunge al primo indice dell'elenco utilizzando InsertAtHead.

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// "list" is created in the previous example
// Update value of index with updated product
Product updatedProduct = GetUpdatedProductByID(11);
list[11] = updatedProduct;

// Get product on sale to insert at the head of the list
Product saleProduct = FetchSaleItem();
list.InsertAtHead(saleProduct);
// Precondition: Cache is already connected

// "list" is created in the previous example
// Update value of index with updated product
Product updatedProduct = GetUpdatedProductByID(11);
list.add(11, updatedProduct);

// Get product on sale to insert at the head of the list
Product saleProduct = FetchSaleItem();
list.insertAtHead(saleProduct);
// This is an async method
// Precondition: Cache is already connected

// "list" is created in the previous example
// Update value of index with updated product
var updatedProduct = this.getUpdatedProductByID(11);
list.add(11, updatedProduct);

// Get product on sale to insert at the head of the list
var saleProduct = this.fetchSaleItem();
list.insertAtHead(fetchSaleItem);

Come recuperare un elenco dalla cache

Puoi recuperare un elenco dalla cache usando GetList, che accetta come parametro una chiave di cache. Questa chiave è il nome dell'elenco specificato durante la creazione dell'elenco.

Avvertenza

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

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// List with this key already exists in cache
string key = "ProductList";

// Get the list and iterate through its items
IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);

if (retrievedList != null)
{
    foreach (var item in retrievedList)
    {
        // Perform operations
    }
}
else
{
    // List does not exist
}
// Precondition: Cache is already connected

// List with this key already exists in cache
String key = "ProductList";

// Get the list and iterate through its items
DistributedList<Product> retrievedList = cache.getDataStructuresManager().getList(key, Product.class);

if (retrievedList != null)
{
    for (var item : retrievedList)
    {
        // Perform operations
    }
} else
{
    // List does not exist
}
// This is an async method
// Precondition: Cache is already connected

// List with this key already exists in cache
var key = "ProductList";

// Get the list and iterate through its items
var manager = await this.cache.getDataStructuresManager();
var retrievedList = await manager.getList(key, ncache.JsonDataType.Object);

if (retrievedList != null)
{
for (var item in retrievedList)
{
    // Perform operations
}
} else
{
// List does not exist
}

Come rimuovere elementi da un elenco

Consiglio

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

È possibile rimuovere da un elenco singoli elementi o un determinato intervallo di elementi. L'esempio di codice seguente rimuove un singolo elemento utilizzando Remove e una gamma di prodotti scaduti utilizzando RemoveRange.

Note:

Se la chiave specificata da rimuovere non esiste, non viene restituito nulla. È possibile verificare il numero di elementi restituiti utilizzando il tipo di ritorno di RemoveRange.

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// List with this key already exists in cache
string key = "ProductList";

// Get list to remove items
IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);

// Get a range of out-of-stock products to be removed
List<Product> outOfStockProducts = FetchOutOfStockProducts();

// Remove each item individually from retrievedList
foreach(Product prod in outOfStockProducts)
{
    retrievedList.Remove(prod);
}

// Get range of discontinued products to be removed
List<Product> discontinuedProducts = FetchDiscontinuedProducts();

// Remove this range from retrievedList
// Number of keys removed is returned
int itemsRemoved = retrievedList.RemoveRange(discontinuedProducts);
// Precondition: Cache is already connected

// List with this key already exists in cache
String key = "ProductList";

// Get list to remove items
DistributedList<Product> retrievedList = cache.getDataStructuresManager().getList(key, Product.class);

// Get a range of out-of-stock products to be removed
List<Product> outOfStockProducts = fetchOutOfStockProducts();

// Remove an individual item from retrieved list
for(Product prod : outOfStockProducts)
{
    retrievedList.remove(prod);
}

// Get range of discontinued products to be removed
List<Product> discontinuedProducts = fetchDiscontinuedProducts();

// Remove this range from retrievedList
// Number of keys removed is returned
int itemsRemoved = retrievedList.removeRange(discontinuedProducts);
// This is an async method
// Precondition: Cache is already connected

// List with this key already exists in cache
var key = "ProductList";

// Get list to remove items
var manager = await this.cache.getDataStructuresManager();
var retrievedList = await manager.getList(key, ncache.JsonDataType.Object);

// Get a range of out-of-stock products to be removed
var outOfStockProducts = this.fetchOutOfStockProducts();

// Remove each item individually from retrievedList
for(const prod of outOfStockProducts){
    await retrievedList.remove(prod);
}

// Get range of discontinued products to be removed
var discontinuedProducts = this.fetchDiscontinuedProducts();

// Remove this range from retrievedList
// Number of keys removed is returned
var itemsRemoved = await retrievedList.removeRangeCollection(discontinuedProducts);

Come registrare le notifiche degli eventi negli elenchi

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

Il seguente esempio di codice registra ItemAdded, ItemUpdatede ItemRemoved eventi della struttura dati sull'elenco. La creazione dell'elenco attiva un ItemAdded evento a livello di cache. L'aggiunta di un elemento all'elenco esistente attiva un ItemAdded evento della struttura dati e un ItemUpdated Evento a livello di cache. DataTypeEventDataFilter specifica la quantità di dati restituiti con l'evento della struttura dati.

Come registrare eventi in un elenco creato

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// Unique cache key for list
string key = "ProductList";

// Create a list of Product type
IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);

// Register ItemAdded, ItemUpdated, ItemRemoved events on list created
// DataTypeNotificationCallback is callback method specified
list.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
        EventType.ItemUpdated | EventType.ItemRemoved,
        DataTypeEventDataFilter.Data);

// Perform operations
// Precondition: Cache is already connected

// Unique cache key for list
String key = "ProductList";

// Create list of product type
DistributedList<Product> list = cache.getDataStructuresManager().createList(key, Product.class);

// Register ItemAdded, ItemUpdated, ItemRemoved events on list created
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
        EventType.ItemUpdated, EventType.ItemRemoved);
list.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations
// This is an async method
// Precondition: Cache is already connected

// Unique cache key for list
var key = "ProductList";

 // Create list
var manager = await this.cache.getDataStructuresManager();
var list = await manager.createList(key, ncache.JsonDataType.Object);


var enumSet = [
    ncache.EventType.ItemAdded,
    ncache.EventType.ItemUpdated,
    ncache.EventType.ItemRemoved
    ];

list.addChangeListener(
this.dataStructureListener, // Make sure this is initialized
enumSet,
ncache.DataTypeEventDataFilter.Data
);

// Perform operations

Come specificare il callback per la notifica degli eventi

  • .NET
  • Java
  • Node.js
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;
        }
    }
};
onDataStructureChanged(collectionName, eventArg)
{
  switch (eventArg.getEventType())
  {
    case ncache.EventType.ItemAdded:
      // Item has been added to the collection
      break;

    case ncache.EventType.ItemUpdated:
      if (eventArg.getCollectionItem() != null)
      {
        // Item has been updated in the collection
        // Perform operations
      }
      break;

    case ncache.EventType.ItemRemoved:
      // Item has been removed from the collection
      break;
  }
}

Come implementare il blocco distribuito su una lista

Gli elenchi possono essere bloccati e sbloccati in modo esplicito per garantire la coerenza dei dati. L'esempio di codice seguente crea un elenco e lo blocca per un periodo di 10 secondi utilizzando bloccare, quindi lo sblocca utilizzando Sbloccare.

  • .NET
  • Java
// Precondition: Cache is already connected

// List exists with key "ProductList"
string key = "ProductList";

// Get list
IDistributedList<Product> list = cache.DataTypeManager.GetList<Product>(key);

// Lock list for 10 seconds
bool isLocked = list.Lock(TimeSpan.FromSeconds(10));

if (isLocked)
{
    // List is successfully locked for 10 seconds
    // Unless explicitly unlocked
}
else
{
    // List is not locked because either:
    // List is not present in the cache
    // List is already locked
}

list.Unlock();
// Precondition: Cache is already connected

// List exists with key "ProductList"
String key = "ProductList";

// Get list
DistributedList<Product> list = cache.getDataStructuresManager().getList(key, Product.class);

// Lock list for 10 seconds
boolean isLocked = list.lock(TimeSpan.FromSeconds(10));

if (isLocked)
{
    // List is successfully locked for 10 seconds
    // Unless explicitly unlocked
} else
{
    // List is not locked because either:
    // List is not present in the cache
    // List is already locked
}
list.unlock();

Risorse addizionali

NCache fornisce un'applicazione di esempio per la struttura dei dati dell'elenco GitHub.

Vedere anche

.NETTO: Alachisoft.NCache.Tipi.dati.client spazio dei nomi.
Giava: com.alachisoft.ncache.client.datastructures spazio dei nomi.
Node.js: Elenco distribuito classe.

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