Comportamento de fila e uso em cache
Uma fila é uma estrutura de dados ordenada que usa o princípio do comportamento First In First Out (FIFO). Você pode usar filas para manter as informações processadas em tempo de execução. Por exemplo, os IDs de candidatura de potenciais candidatos para uma empresa podem ser armazenados numa fila. Como a fila é de natureza FIFO, o primeiro candidato a se inscrever será entrevistado primeiro e assim sucessivamente.
NCache aprimora ainda mais a estrutura de dados da fila, fornecendo NCache- recursos específicos, como Grupos, Tags, Expiration, Bloqueio, Dependências, e mais. Nesse cenário, a empresa pode especificar um grupo em uma fila de pessoas que se candidataram a cargos administrativos.
Comportamento
- Uma fila pode ser de qualquer tipo primitivo ou objeto personalizado.
- Uma fila de
CacheItem
e filas aninhadas ainda não são suportadas.
- As filas são nomeadas. Portanto, você precisa fornecer uma chave de cache exclusiva para uma fila.
- Nulo não é um tipo de valor com suporte.
- Valores duplicados são suportados.
Pré-requisitos
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: ICache, IDistributedQueue, IDataTypeManager, contém, Copiar para, ParaArray, Espreitar, ObterQueue, Desenfileirar, Enfileirar, Criar fila, CadastroNotificação, DataTypeDataNotificationCallback, Eventtype, DataTypeEventDataFilter, Travar, Destravar.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: Esconderijo, Fila Distribuída, criarFila, getFila, contém, trancar, destravar, Eventtype, getEventType, addChangeListener, getDataStructuresManager, onDataStructureChanged, DataTypeEventDataFilter, DataStructureDataChangeListener, DataStructureEventArg, getCollectionItem.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para obter detalhes da API, consulte: Esconderijo, Fila Distribuída, getDataStructuresManager, criarFila, adicionar, getFila, contém, copiar para, paraArray, espreitar, remover, Eventtype, DataStructureDataChangeListener, addChangeListener, DataTypeEventDataFilter, DataStructureEventArg, getEventType, getCollectionItem.
- Para aprender sobre os pré-requisitos padrão necessários para trabalhar com todos os NCache recursos do lado do cliente, consulte a página fornecida em Pré-requisitos da API do lado do cliente.
- Para detalhes da API, consulte: Esconderijo, DataStructureManager, get_data_estruturas_manager, Fila Distribuída, contém, adicionar, get_iterador, remover, add_change_listener, criar_fila, get_queue, get_event_type, DataTypeEventDataFilter, EventDataFilter, DataStructureDataChangeListener, onDataStructureChanged.
Criar fila e adicionar dados
O exemplo de código a seguir mostra como uma fila de Candidato tipo pode ser criado no cache em relação à chave de cache CandidateQueue e como os itens são adicionados à fila.
// 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")
O exemplo de código a seguir busca uma fila do cache usando GetQueue
e, em seguida, verifica se existe um item na fila ou não usando Contains
. Como obter um item do início da fila sem removê-lo usando Peek
. Para copiar toda a fila de origem para a matriz de destino usando CopyTo
, e para copiar esta fila em uma 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")
Remover itens da fila
Os itens podem ser removidos de uma fila de maneira FIFO. O exemplo de código a seguir remove o primeiro candidato da fila.
// 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 garantir que a operação seja à prova de falhas, é recomendável lidar com possíveis exceções em seu aplicativo, conforme explicado em Como lidar com falhas.
Notificações de eventos em filas
Você pode registrar eventos de cache, eventos baseados em chave e eventos de estrutura de dados em uma estrutura de dados, como uma fila. Para comportamento, consulte comportamento sábio em recursos.
O exemplo de código a seguir registra um evento de cache de ItemAdded
e ItemUpdated
bem como registra um evento para ItemAdded
e ItemUpdated
na fila no cache. Depois que uma fila é criada no cache, um ItemAdded
evento em nível de cache é disparado. No entanto, uma vez que um item é adicionado à fila, um ItemAdded
evento de estrutura de dados é acionado e um ItemUpdated
evento de nível de cache é acionado.
Registrar evento na fila criada
// 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 retorno de chamada para notificação 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)
Bloqueando filas
As filas podem ser bloqueadas e desbloqueadas explicitamente para garantir a consistência dos dados. O exemplo de código a seguir cria uma fila e a bloqueia por um período de 10 segundos usando Travar e, em seguida, desbloqueia usando Destravar.
// 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 adicionais
NCache fornece um aplicativo de amostra para a estrutura de dados da fila em GitHub.
Veja também
.INTERNET: Alachisoft.NCache.Client.DataTypes espaço para nome.
Java: com.alachisoft.ncache.client.dataestruturas espaço para nome.
Node.js: Fila Distribuída classe.
Pitão: ncache.client.dataestruturas classe.