Elenca il comportamento e l'utilizzo nella cache
Un elenco è una struttura di dati non ordinati in cui i dati possono essere aggiunti o rimossi dall'elenco. Ad esempio, le liste mantengono i prodotti aggiunti a un carrello per un sito di e-commerce. Supponiamo che un utente aggiunga al carrello i prodotti Umbrella, Green Apples e Coffee. Prima di effettuare la transazione, il prodotto Mele verdi viene rimosso e viene aggiunto un nuovo prodotto Pere. Questo è possibile perché puoi aggiornare l'elenco da qualsiasi punto all'interno di esso.
NCache migliora ulteriormente la struttura dei dati dell'elenco fornendo NCache-funzioni specifiche come ATTIVITA' E GRUPPI, tag, Scadenza, Blocco, dipendenze, e altro ancora. In questo scenario, l'azienda desidera che l'elenco del carrello venga mantenuto solo finché la sessione è attiva. Pertanto, la scadenza può essere associata a ogni elenco creato uguale al valore di timeout della sessione.
Comportamento
- Un elenco può essere di qualsiasi tipo primitivo o oggetto personalizzato.
- Un elenco di
CacheItem
e gli elenchi nidificati non sono ancora supportati.
- Gli elenchi sono accessibili direttamente dall'indice.
- Gli elenchi sono nominati. Pertanto, è necessario fornire una chiave cache univoca per un elenco.
- Null non è un tipo di valore supportato.
- Sono supportati valori duplicati.
Prerequisiti
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: ICache, IDdistributedList, IdataTypeManager, Crea lista, Aggiungi intervallo, Inserisci in testa, OttieniLista, Rimuovi intervallo, Ilist, Notifica di registrazione, DataTypeDataNotificationRichiamata, Tipo di evento, DataTypeEventDataFilter, bloccare, Sbloccare.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- 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.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: Cache, Elenco distribuito, getDataStructuresManager, creareLista, aggiungiRange, getList, inserisci in testa, rimuovere, rimuoviRange, DataStructureDataChangeListener, bloccare, Tipo di evento, addChangeListener, DataTypeEventDataFilter , DataStructureEventArg, getEventType, getCollectionItem, sbloccare, DataStructureDataChangeListener.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Per i dettagli dell'API fare riferimento a: Cache, Elenco distribuito, Gestore struttura dati, get_data_structures_manager, crea_lista, aggiungi_intervallo, get_list, inserisci_in_testa, get_iteratore, rimuovi_intervallo, get_event_type, add_change_listener , DataTypeEventDataFilter, EventDataFilter.
Crea un elenco e aggiungi i dati
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
.
// Precondition: Cache must be 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);
// Precondition: Cache must be connected
// Specify unique cache key for list
String key = "ProductList";
// Create a 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));
// This is an async method
// Precondition: Cache must be 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 in 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);
# Precondition: Cache must be connected
# Specify unique cache key for list
key = "ProductList"
# Create list
manager = cache.get_data_structures_manager()
product_list = manager.create_list(key, Product)
# Get products to add to list
products = fetch_products()
for product in products:
# Add products to list
product_list.add(product)
# Get new products
new_products = fetch_new_products()
# Append list of new Products to existing list
product_list.add_range(new_products)
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.
Aggiorna elementi nell'elenco
È possibile aggiornare gli elenchi e gli elementi in essi contenuti utilizzando gli indici poiché è possibile accedere agli elenchi tramite index. L'esempio di codice seguente aggiorna un valore in un elenco esistente (creato nell'esempio precedente) utilizzando l'indice. Quindi ottiene un articolo in vendita e lo aggiunge al primo indice dell'elenco utilizzando InsertAtHead
.
// "list" is created in previous example
// Update value of index with updated product
Product updatedProduct = GetUpdatedProductByID(11);
list[11] = updatedProduct;
// Get product on sale to insert at head of List
Product saleProduct = FetchSaleItem();
list.InsertAtHead(saleProduct);
// Precondition: Cache is already connected
// "list" is created in previous example
// Update value of index with updated product
Product updatedProduct = getUpdatedProductByID(11);
list.add(11, updatedProduct);
// Get product on sale to insert at head of List
Product saleProduct = fetchSaleItem();
list.insertAtHead(saleProduct);
// This is an async method
// Precondition: Cache is already connected
// "list" is created in 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 head of List
var saleProduct = this.fetchSaleItem();
list.insertAtHead(fetchSaleItem);
# Precondition: Cache is already connected
# "product_list" is created in previous example
# Update value of index with updated product
updated_product = get_updated_product_by_id(1011)
product_list .add(updated_product, 1011)
# Get product on sale to insert at head of List
sale_product = fetch_sale_item()
product_list .insert_at_head(sale_product)
Recupera l'elenco dalla cache
Puoi recuperare un elenco dalla cache usando GetList
che accetta una chiave di cache come parametro. Questa chiave è il nome dell'elenco specificato durante la creazione dell'elenco.
avvertimento
Se l'elemento recuperato non è di tipo Elenco, a Type mismatch
viene generata un'eccezione.
// List with this key already exists in cache
string key = "ProductList";
// Get list and show items of list
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 list and show items of list
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 list and show items of list
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
}
# Precondition: Cache is already connected
# List with this key already exists in cache
key = "ProductList"
# Get list and show items of list
manager = cache.get_data_structures_manager()
retrieved_list = manager.get_list(key, Product)
if retrieved_list is not None:
for item in retrieved_list.get_iterator():
# Perform operations
print(item)
else:
# List does not exist
print("List not found")
Rimuovi elementi dall'elenco
È 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 articoli per i prodotti scaduti che utilizzano RemoveRange
.
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 RemoveRange
.
// 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 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 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 range of out of stock products to be removed
var outOfStockProducts = this.fetchOutOfStockProducts();
// Remove an individual item from retrieved list
for(var prod in outOfStockProducts){
await retrievedList.remove(prod);
}
// Get range of discontinued json datatype products to be removed
var discontinuedProducts = this.fetchDiscontinuedProducts();
// Remove this range from retrievedList
// Number of keys removed is returned
var itemsRemoved = await retrievedList.removeRange(discontinuedProducts);
# Precondition: Cache is already connected
# List with this key already exists in cache
key = "ProductList"
# Get list to remove items
manager = cache.get_data_structures_manager()
retrieved_list = manager.get_list(key, Product)
# Get range of expired products to be removed
items_to_remove = fetch_expired_products()
# Remove this range from retrievedList
# Number of keys removed is returned
items_removed = retrieved_list.remove_range(collection=items_to_remove)
Notifiche di eventi sugli 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à.
L'esempio di codice seguente registra un evento cache di ItemAdded
ed ItemUpdated
. Registra anche un evento per ItemAdded
ed ItemUpdated
nell'elenco nella cache. Dopo aver creato un elenco nella cache, an ItemAdded
viene generato un evento a livello di cache. Tuttavia, una volta aggiunto un elemento all'elenco, an ItemAdded
evento della struttura dei dati, insieme a un ItemUpdated
viene attivato l'evento a livello di cache. UN DataTypeEventDataFilter
è specificato per quantificare la quantità di informazioni restituite all'esecuzione di un evento. Gli eventi, così registrati, forniscono quindi all'utente le informazioni basate su questi filtri di dati.
Registra l'evento nell'elenco creato
// Pre-condition: Cache is connected
// Unique cache key for list
string key = "ProductList";
// Create 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
// dataChangeListener is the specified callback method
DataStructureDataChangeListener dataChangeListener = dataStructureListener.onDataStructureChanged(collectionName, args);
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
EventType.ItemUpdated, EventType.ItemRemoved);
list.addChangeListener(dataChangeListener, 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 list = await this.cache
.getDataStructuresManager()
.createList(key, ncache.JsonDataType.Object);
// Register ItemAdded, ItemUpdated, ItemRemoved events on list created
// dataChangeListener is the specified callback method
var dataChangeListener = this.dataStructureListener.onDataStructureChanged(
collectionName,
args
);
var enumSet = enumSet.of(
ncache.EventType.ItemAdded,
ncache.EventType.ItemUpdated,
ncache.EventType.ItemRemoved
);
list.addChangeListener(
dataChangeListener,
enumSet,
ncache.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 list
key = "ProductList"
# Create list
product_list = cache.get_data_structures_manager().create_list(key, Product)
# Register ItemAdded, ItemUpdated, ItemRemoved events on list created
events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]
product_list.add_change_listener(datastructure_callback_function, events_list, ncache.DataTypeEventDataFilter.DATA)
Specificare la richiamata per la notifica dell'evento
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;
}
}
};
dataStructureListener = new ncache.DataStructureDataChangeListener();
{
function onDataStructureChanged(collection, dataStructureEventArg) {
switch (dataStructureEventArg.getEventType()) {
case ncache.EventType.ItemAdded:
//Item has been added to the collection
break;
case ncache.EventType.ItemUpdated:
if (dataStructureEventArg.getCollectionItem() != null) {
//Item has been updated in the collection
// perform operations
}
break;
case ncache.EventType.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)
Liste di blocco
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.
// 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();
// Preconditions: 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.strutture.dati.client spazio dei nomi.
Node.js: Elenco distribuito classe.
Pitone: ncache.strutture.dati.client classe.