Warteschlangenverhalten und Nutzung im Cache
Eine Warteschlange ist eine geordnete Datenstruktur, die das Prinzip des FIFO-Verhaltens (First In First Out) verwendet. Sie können Warteschlangen verwenden, um Informationen zu verwalten, die zur Laufzeit verarbeitet werden. Beispielsweise können die Bewerbungs-IDs potenzieller Kandidaten für ein Unternehmen in einer Warteschlange gespeichert werden. Da es sich bei der Warteschlange um eine FIFO-Warteschlange handelt, wird der erste Kandidat, der sich bewirbt, zuerst interviewt und so weiter.
NCache Verbessert die Warteschlangendatenstruktur weiter durch die Bereitstellung NCache-Spezifische Funktionen wie z Groups, Schlüsselwörter, Ablauf, Sperrung, Abhängigkeiten, und mehr. In diesem Szenario kann das Unternehmen eine Gruppe für eine Warteschlange von Personen festlegen, die sich für Verwaltungsstellen beworben haben.
Verhalten
- Eine Warteschlange kann einen beliebigen primitiven Typ oder ein benutzerdefiniertes Objekt haben.
- Eine Schlange von
CacheItem
und verschachtelte Warteschlangen werden noch nicht unterstützt.
- Warteschlangen werden benannt. Daher müssen Sie einen eindeutigen Cache-Schlüssel für eine Warteschlange bereitstellen.
- Null ist kein unterstützter Werttyp.
- Doppelte Werte werden unterstützt.
Voraussetzungen:
- Lernen Sie die Standardvoraussetzungen kennen, die für die Arbeit mit allen erforderlich sind NCache Weitere Informationen zu clientseitigen Funktionen finden Sie auf der angegebenen Seite Clientseitige API-Voraussetzungen.
- Einzelheiten zur API finden Sie unter: ICache, IDistributedQueue, IDataTypeManager, Enthält, Kopie an, ZuArray, Spähen, GetQueue, Aus der Warteschlange, Enqueue, Warteschlange erstellen, Registrierungsbenachrichtigung, DataTypeDataNotificationCallback, Ereignistyp, DataTypeEventDataFilter, Zahnscheiben, öffne es.
- Lernen Sie die Standardvoraussetzungen kennen, die für die Arbeit mit allen erforderlich sind NCache Weitere Informationen zu clientseitigen Funktionen finden Sie auf der angegebenen Seite Clientseitige API-Voraussetzungen.
- Einzelheiten zur API finden Sie unter: Cache-Speicher, Verteilte Warteschlange, createQueue, getQueue, enthält, sperren, öffnen, Ereignistyp, GetEventType, Addchangelistener, getDataStructuresManager, onDataStructureChanged, DataTypeEventDataFilter, DataStructureDataChangeListener, DataStructureEventArg, getCollectionItem.
- Lernen Sie die Standardvoraussetzungen kennen, die für die Arbeit mit allen erforderlich sind NCache Weitere Informationen zu clientseitigen Funktionen finden Sie auf der angegebenen Seite Clientseitige API-Voraussetzungen.
- Einzelheiten zur API finden Sie unter: Cache-Speicher, Verteilte Warteschlange, getDataStructuresManager, createQueue, hinzufügen, getQueue, enthält, Kopieren nach, zuArray, spähen, entfernen, Ereignistyp, DataStructureDataChangeListener, Addchangelistener, DataTypeEventDataFilter, DataStructureEventArg, GetEventType, getCollectionItem.
- Lernen Sie die Standardvoraussetzungen kennen, die für die Arbeit mit allen erforderlich sind NCache Weitere Informationen zu clientseitigen Funktionen finden Sie auf der angegebenen Seite Clientseitige API-Voraussetzungen.
- Einzelheiten zur API finden Sie unter: Cache-Speicher, DataStructureManager, get_data_structures_manager, Verteilte Warteschlange, enthält, hinzufügen, get_iterator, entfernen, add_change_listener, create_queue, get_queue, get_event_type, DataTypeEventDataFilter, Ereignisdatenfilter, DataStructureDataChangeListener, onDataStructureChanged.
Erstellen Sie eine Warteschlange und fügen Sie Daten hinzu
Das folgende Codebeispiel zeigt, wie eine Warteschlange von Kandidat Der Typ kann im Cache anhand des Cache-Schlüssels erstellt werden Kandidatenwarteschlange und wie Elemente zur Warteschlange hinzugefügt werden.
// 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")
Das folgende Codebeispiel ruft mithilfe von eine Warteschlange aus dem Cache ab GetQueue
und prüft dann, ob ein Element in der Warteschlange vorhanden ist oder nicht Contains
. So erhalten Sie ein Element vom Anfang der Warteschlange, ohne es mit zu entfernen Peek
. Zum Kopieren der gesamten Quellwarteschlange in das Zielarray mit CopyTo
, und um diese Warteschlange mit in ein eindimensionales Array zu kopieren 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")
Elemente aus der Warteschlange entfernen
Elemente können im FIFO-Verfahren aus einer Warteschlange entfernt werden. Das folgende Codebeispiel entfernt den ersten Kandidaten aus der Warteschlange.
// 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
Um sicherzustellen, dass der Vorgang ausfallsicher ist, wird empfohlen, alle potenziellen Ausnahmen in Ihrer Anwendung zu behandeln, wie in erläutert Umgang mit Fehlern.
Ereignisbenachrichtigungen in Warteschlangen
Sie können Cache-Ereignisse, schlüsselbasierte Ereignisse und Datenstrukturereignisse in einer Datenstruktur wie einer Warteschlange registrieren. Informationen zum Verhalten finden Sie unter merkmalsorientiertes Verhalten.
Das folgende Codebeispiel registriert ein Cache-Ereignis von ItemAdded
und ItemUpdated
sowie eine Veranstaltung für registrieren ItemAdded
und ItemUpdated
in der Warteschlange im Cache. Sobald eine Warteschlange im Cache erstellt wurde, wird eine ItemAdded
Ein Ereignis auf Cache-Ebene wird ausgelöst. Sobald jedoch ein Element zur Warteschlange hinzugefügt wird, wird ein ItemAdded
Das Datenstrukturereignis wird ausgelöst und ein ItemUpdated
Das Ereignis auf Cache-Ebene wird ausgelöst.
Ereignis in der erstellten Warteschlange registrieren
// 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)
Geben Sie einen Rückruf für die Ereignisbenachrichtigung an
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)
Warteschlangen sperren
Warteschlangen können explizit gesperrt und entsperrt werden, um die Datenkonsistenz sicherzustellen. Das folgende Codebeispiel erstellt eine Warteschlange und sperrt sie für einen Zeitraum von 10 Sekunden mit Zahnscheiben und entsperrt es dann mit öffne es.
// 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();
Weitere Informationen
NCache stellt eine Beispielanwendung für die Warteschlangendatenstruktur bereit GitHub.
Siehe auch
.NETZ: Alachisoft.NCache.Client.Datentypen Namespace.
Java: com.alachisoft.ncache.client.Datenstrukturen Namespace.
Node.js: Verteilte Warteschlange Klasse.
Python: ncache.client.Datenstrukturen Klasse.