Comportamiento y uso de listas en caché
Una lista es una estructura de datos desordenada en la que se pueden agregar o eliminar datos de la lista. Por ejemplo, las listas mantienen los productos agregados a un carrito para un sitio web de comercio electrónico. Supongamos que un usuario agrega los productos Umbrella, Green Apples y Coffee al carrito. Antes de realizar la transacción, se elimina el producto Manzanas Verdes y se agrega un nuevo producto Peras. Esto es posible porque puede actualizar la lista desde cualquier punto dentro de sí misma.
NCache mejora aún más la estructura de datos de la lista al proporcionar NCache-características específicas como Grupos, Etiquetas, Vencimiento, Cerraduras, Dependencias, y más. En este escenario, la empresa desea que la lista de carritos se mantenga solo mientras la sesión esté activa. Por lo tanto, la caducidad se puede asociar con cada lista creada que sea igual al valor de tiempo de espera de la sesión.
Comportamiento
- Una lista puede ser de cualquier tipo primitivo u objeto personalizado.
- Una lista de los
CacheItem
y las listas anidadas aún no son compatibles.
- Se puede acceder directamente a las listas por índice.
- Las listas se nombran. Por lo tanto, debe proporcionar una clave de caché única para una lista.
- Nulo no es un tipo de valor admitido.
- Se admiten valores duplicados.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: Dolor, Lista distribuida, Administrador de tipo de datos IData, Crear lista, AgregarRango, Insertar en cabeza, ObtenerLista, Quitar rango, ILista, RegistroNotificación, Tipo de datosNotificación de datosDevolución de llamada, Tipo de evento, Tipo de datosEventoFiltro de datos, Bloquear, descubrir.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: cache, Lista distribuida, getDataStructuresManager, Crear lista, añadirRango, eliminarRango, insertarEnCabeza, obtenerLista, Estructura de datosDataChangeListener, onDataStructureCambiado, agregarChangeListener, Tipo de evento, obtener tipo de evento, Tipo de datosEventoFiltro de datos, DataStructureEventArgDataStructureEventArg, obtener artículo de colección, bloquear, desbloquear.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: cache, Lista distribuida, getDataStructuresManager, Crear lista, añadirRango, obtenerLista, insertarEnCabeza, remove, eliminarRango, Estructura de datosDataChangeListener, bloquear, Tipo de evento, agregarChangeListener, Tipo de datosEventoFiltro de datos , DataStructureEventArgDataStructureEventArg, obtener tipo de evento, obtener artículo de colección, desbloquear, Estructura de datosDataChangeListener.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: cache, Lista distribuida, Administrador de estructuras de datos, get_data_structures_manager, Crear lista, añadir_rango, obtener_lista, insertar_en_cabeza, obtener_iterador, eliminar_rango, get_event_type, añadir_cambio_escucha , Tipo de datosEventoFiltro de datos, Filtro de datos de evento.
Cree una lista y agregue los datos
El siguiente ejemplo de código muestra cómo una lista de Producto Los tipos se pueden crear en el caché usando CreateList
contra la clave de caché Lista de productos. Los productos se agregan a la lista usando Add
, y luego se agrega una nueva gama de productos a la lista usando 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
Para garantizar que la operación sea a prueba de fallas, se recomienda manejar cualquier posible excepción dentro de su aplicación, como se explica en Manejo de fallas.
Actualizar elementos en la lista
Puede actualizar las listas y los elementos en ellas utilizando índices, ya que se puede acceder a las listas a través de índice. El siguiente ejemplo de código actualiza un valor en una lista existente (creada en el ejemplo anterior) usando el índice. Luego obtiene un artículo de venta y lo agrega al primer índice de la lista usando 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)
Obtener lista de caché
Puede obtener una lista del caché usando GetList
que toma una clave de caché como parámetro. Esta clave es el nombre de la lista especificada durante la creación de la lista.
advertencia
Si el elemento que se busca no es del tipo Lista, un Type mismatch
Se lanza una excepción.
// 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")
Eliminar elementos de la lista
Los elementos individuales o un rango determinado de elementos se pueden eliminar de una lista. El siguiente ejemplo de código elimina un elemento individual usando Remove
y una gama de artículos para los productos vencidos usando RemoveRange
.
Note
Si la clave especificada para eliminar no existe, no se devuelve nada. Puede verificar el número de claves devueltas utilizando el tipo de devolución de 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)
Notificaciones de eventos en listas
Puede registrar eventos de caché, eventos basados en claves y eventos de estructura de datos en una estructura de datos como una lista. Para el comportamiento, consulte comportamiento en función de las características.
El siguiente ejemplo de código registra un evento de caché de ItemAdded
y ItemUpdated
. También registra un evento para ItemAdded
y ItemUpdated
en la lista en el caché. Una vez que crea una lista en el caché, un ItemAdded
Se activa el evento a nivel de caché. Sin embargo, una vez que agrega un elemento a la lista, un ItemAdded
evento de estructura de datos, junto con un ItemUpdated
Se activa el evento de nivel de caché. A DataTypeEventDataFilter
se especifica para cuantificar la cantidad de información devuelta tras la ejecución de un evento. Los eventos, así registrados, luego brindan al usuario la información basada en estos filtros de datos.
Registrar evento en lista creada
// 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)
Especificar devolución de llamada para notificación de eventos
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)
Listas de bloqueo
Las listas se pueden bloquear y desbloquear explícitamente para garantizar la coherencia de los datos. El siguiente ejemplo de código crea una lista y la bloquea durante un período de 10 segundos usando Bloqueary luego lo desbloquea usando descubrir.
// 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();
Recursos adicionales
NCache proporciona una aplicación de muestra para la estructura de datos de lista en GitHub.
Vea también
.NETO: Alachisoft.NCache.Client.Tipos de datos espacio de nombres
Java: com.alachisoft.ncache.cliente.estructuras de datos espacio de nombres
Nodo.js: Lista distribuida clase.
Pitón: ncache.cliente.estructuras de datos clase.