Comportamiento y uso de la cola en caché
Una cola es una estructura de datos ordenada que utiliza el principio de comportamiento primero en entrar, primero en salir (FIFO). Puede utilizar colas para mantener la información que se procesa en tiempo de ejecución. Por ejemplo, los ID de solicitud de candidatos potenciales para una empresa se pueden almacenar en una cola. Como la cola es de naturaleza FIFO, el primer candidato que presente su solicitud será entrevistado primero, y así sucesivamente.
NCache mejora aún más la estructura de datos de la cola al proporcionar NCache-características específicas como Grupos, Etiquetas, Vencimiento, Cerraduras, Dependencias, y más. En este escenario, la empresa puede especificar un grupo en una cola de personas que solicitaron trabajos administrativos.
Comportamiento
- Una cola puede ser de cualquier tipo primitivo u objeto personalizado.
- una cola de
CacheItem
y las colas anidadas aún no son compatibles.
- Las colas se nombran. Por lo tanto, debe proporcionar una clave de caché única para una cola.
- 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, IDistributedQueueIDistributedQueue, Administrador de tipo de datos IData, contiene, CopyTo, A la matriz, Ojeada, ObtenerCola, Quitar de la cola, Poner en cola, Crear cola, 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, Cola distribuida, crear cola, obtenerCola, contiene, bloquear, desbloquear, Tipo de evento, obtener tipo de evento, agregarChangeListener, getDataStructuresManager, onDataStructureCambiado, Tipo de datosEventoFiltro de datos, Estructura de datosDataChangeListener, DataStructureEventArgDataStructureEventArg, obtener artículo de colección.
- 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, Cola distribuida, getDataStructuresManager, crear cola, add, obtenerCola, contiene, copiar a, aArray, ojeada, remove, Tipo de evento, Estructura de datosDataChangeListener, agregarChangeListener, Tipo de datosEventoFiltro de datos, DataStructureEventArgDataStructureEventArg, obtener tipo de evento, obtener artículo de colección.
- 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, Administrador de estructuras de datos, get_data_structures_manager, Cola distribuida, contiene, add, obtener_iterador, remove, añadir_cambio_escucha, crear_cola, obtener_cola, get_event_type, Tipo de datosEventoFiltro de datos, Filtro de datos de evento, Estructura de datosDataChangeListener, onDataStructureCambiado.
Crear cola y agregar datos
El siguiente ejemplo de código muestra cómo una cola de Candidato el tipo se puede crear en el caché contra la clave de caché cola de candidatos y cómo se agregan elementos a la cola.
// Precondition: Cache must be connected
// Specify unique cache key for queue
string key = "CandidateQueue";
// Create Queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);
Candidate[] candidates = FetchCandidates();
foreach(var candidate in candidates)
{
// Add candidates to queue
queue.Enqueue(candidate);
}
// Precondition: Cache must be connected
// Specify unique cache key for queue
String key = "CandidateQueue";
// Create Queue of Candidate type
DistributedQueue<Candidate> queue = cache.getDataStructuresManager().createQueue(key, Candidate.class);
Candidate[] candidates = fetchCandidates();
for (var candidate : candidates) {
// Add candidates to queue
queue.add(candidate);
}
// This is an async method
// Precondition: Cache must be connected
// Specify unique cache key for queue
var key = "CandidateQueue";
// Create Queue
var manager = await this.cache.getDataStructuresManager();
var queue = await manager.createQueue(key, ncache.JsonDataType.Object);
var candidates = this.fetchCandidates();
for (var candidate in candidates) {
// Add candidates to queue
queue.add(candidate);
}
# Precondition: Cache must be connected
# Specify unique cache key for queue
key = "CandidateQueue"
# Create Queue
manager = cache.get_data_structures_manager()
queue = manager.create_queue(key, Candidate)
candidates = fetch_candidates()
for candidate in candidates:
# Add candidates to queue
queue.add(candidate)
# Check if a candidate exists against given ID
candidate = get_candidate_by_id(1002)
if queue.contains(candidate):
# Candidate exists with this ID
print("Candidate found")
El siguiente ejemplo de código obtiene una cola del caché usando GetQueue
y luego verifica si existe un elemento en la cola o no usando Contains
. Cómo obtener un elemento desde el principio de la cola sin eliminarlo usando Peek
. Para copiar toda la cola de origen a la matriz de destino usando CopyTo
y copiar esta cola en una matriz unidimensional usando ToArray
.
// Queue with this key already exists in cache
string key = "CandidateQueue";
// Get queue and show items of queue
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Get any candidate ID
Candidate candidate = GetCandidateByID(1002);
// Check whether queue contains the a particular candidate or not
if(retrievedQueue.Contains(candidate))
{
// Candidate exists with this ID
}
// List of candidate's for the queue to be copied into
Candidate[] candidates = new Candidate[retrievedQueue.Count];
// Copy the queue to another array
retrievedQueue.CopyTo(candidates, 0);
// Copy queue to one-dimensional array
candidates = retrievedQueue.ToArray();
// Get an item at beginning from queue without removing
Candidate firstCandidate = retrievedQueue.Peek();
// Precondition: Cache is already connected
// Queue with this key already exists in cache
String key = "CandidateQueue";
// Get queue and show items of queue
DistributedQueue<Candidate> retrievedQueue = cache.getDataStructuresManager().getQueue(key, Candidate.class);
// Get any candidate's ID
Candidate candidate = getCandidateByID(1002);
// Check whether queue contains the a particular candidate or not
if(retrievedQueue.contains(candidate))
{
// Candidate exists with this ID
}
// List of candidates for the queue to be copied into
Candidate[] candidates = new Candidate[retrievedQueue.size()];
// Copy the queue to another array
retrievedQueue.copyTo(candidates, 0);
// Copy queue to one-dimensional array
candidates = retrievedQueue.toArray();
// Get an item at beginning from queue without removing
Candidate firstCandidate = retrievedQueue.peek();
// This is an async method
// Precondition: Cache is already connected
// Queue with this key already exists in cache
var key = "CandidateQueue";
// Get queue and show items of queue
var manager = await this.cache.getDataStructuresManager();
var retrievedQueue = await manager.getQueue(key, ncache.JsonDataType.Object);
// Get any candidate's ID
var candidate = this.getCandidateByID(1002);
// Check whether queue contains the a particular candidate or not
if(retrievedQueue.contains(candidate))
{
// Candidate exists with this ID
}
// List of candidates for the queue to be copied into
var candidates = new Candidate[retrievedQueue.length];
// Copy the queue to another array
retrievedQueue.copyTo(candidates, 0);
// Copy queue to one-dimensional array
var candidates = retrievedQueue.toArray();
// Get an item at beginning from queue without removing
var firstCandidate = retrievedQueue.peek();
# Precondition: Cache is already connected
# Queue with this key already exists in cache
key = "CandidateQueue"
# Get queue and show items of queue
manager = cache.get_data_structures_manager()
retrieved_queue = manager.get_queue(key, Candidate)
if retrieved_queue is not None:
for item in retrieved_queue.get_iterator():
# Perform operations
print(item)
else:
# Queue does not exist
print("Queue not found")
Eliminar elementos de la cola
Los elementos se pueden eliminar de una cola de forma FIFO. El siguiente ejemplo de código elimina el primer candidato de la cola.
// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Remove first item of queue
retrievedQueue.Dequeue();
// Precondition: Cache must be connected
// Queue with this key already exists in cache
String key = "CandidateQueue";
DistributedQueue<Candidate> retrievedQueue = cache.getDataStructuresManager().getQueue(key, Candidate.class);
// Remove first item of queue
retrievedQueue.remove();
// This is an async method
// Precondition: Cache must be connected
// Queue with this key already exists in cache
var key = "CandidateQueue";
var manager = await this.cache.getDataStructuresManager();
var retrievedQueue = await manager.getQueue(key, ncache.JsonDataType.Object);
// Remove first item of queue
await retrievedQueue.remove();
# Precondition: Cache must be connected
# Queue with this key already exists in cache
key = "CandidateQueue"
manager = cache.get_data_structures_manager()
retrieved_queue = manager.get_queue(key, Candidate)
# Remove first item of queue
retrieved_queue.remove()
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.
Notificaciones de eventos en colas
Puede registrar eventos de caché, eventos basados en claves y eventos de estructura de datos en una estructura de datos como una cola. Para el comportamiento, consulte comportamiento inteligente.
El siguiente ejemplo de código registra un evento de caché de ItemAdded
y ItemUpdated
así como registra un evento para ItemAdded
y ItemUpdated
en la cola en el caché. Una vez que se crea una cola en el caché, un ItemAdded
Se activa el evento a nivel de caché. Sin embargo, una vez que se agrega un elemento a la cola, un ItemAdded
se activa un evento de estructura de datos y ItemUpdated
se activa el evento de nivel de caché.
Registrar evento en la cola creada
// Unique cache key for queue
string key = "CandidateQueue";
// Create queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on queue created
// DataTypeNotificationCallback is callback method specified
queue.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
DataTypeEventDataFilter.Data);
// Perform operations
// Precondition: Cache is already connected
// Unique cache key for the queue
String key = "CandidateQueue";
// Create queue of candidate type
DistributedQueue<Candidate> queue = cache.getDataStructuresManager().createQueue(key, Candidate.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);
queue.addChangeListener(dataChangeListener, enumSet, DataTypeEventDataFilter.Data);
// Perform operations
// This is an async method
// Precondition: Cache is already connected
// Unique cache key for the queue
var key = "CandidateQueue";
// Create queue of candidate type
var queue = await this.cache
.getDataStructuresManager()
.createQueue(key, ncache.JsonDataType.Object);
// Create EnumSet of event types
var enumSet = enumSet.of(
ncache.EventType.ItemAdded,
ncache.EventType.ItemUpdated,
ncache.EventType.ItemRemoved
);
// Register ItemAdded, ItemUpdated, ItemRemoved events on queue created
// dataChangeListener is the specified callback method
var dataChangeListener = this.dataStructureListener.onDataStructureChanged(
collectionName,
args
);
queue.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 queue
key = "CandidateQueue"
# Create queue
queue = cache.get_data_structures_manager().create_queue(key, Candidate)
# Register ItemAdded, ItemUpdated, ItemRemoved events on queue created
events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]
queue.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)
Colas de bloqueo
Las colas se pueden bloquear y desbloquear explícitamente para garantizar la coherencia de los datos. El siguiente ejemplo de código crea una cola y la bloquea durante un período de 10 segundos usando Bloquear y luego lo desbloquea usando descubrir.
// Queue exists with key "CandidateQueue" cache key
string key = "CandidateQueue";
// Get queue
IDistributedQueue<Candidate> queue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Lock queue for 10 seconds
bool isLocked = queue.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// Queue is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// Queue is not locked because either:
// Queue is not present in the cache
// Queue is already locked
}
queue.Unlock();
// Preconditions: Cache is already connected
// Queue exists with key "CandidateQueue" cache key
String key = "CandidateQueue";
// Get queue
DistributedQueue<Candidate> queue = cache.getDataStructuresManager().getQueue(key, Candidate.class);
// Lock queue for 10 seconds
boolean isLocked = queue.lock(TimeSpan.FromSeconds(10));
if (isLocked) {
// Queue is successfully locked for 10 seconds
// Unless explicitly unlocked
} else {
// Queue is not locked because either:
// Queue is not present in the cache
// Queue is already locked
}
queue.unlock();
Recursos adicionales
NCache proporciona una aplicación de muestra para la estructura de datos de la cola 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: Cola distribuida clase.
Pitón: ncache.cliente.estructuras de datos clase.