• Facebook
  • Twitter
  • Youtube
  • Allineato
  • RSS
  • Docs
  • Confronti
  • Blog
  • Scaricare
  • Contattaci
Scaricare
Mostra/Nascondi sommario

Comportamento della coda e utilizzo nella cache

Una coda è una struttura dati ordinata che utilizza il principio del comportamento First-In-First-Out (FIFO). NCache Distributed Queue consente di aggiungere e rimuovere elementi dalla coda su più istanze dell'applicazione con elevata coerenza. Offre supporto integrato per operazioni in blocco e notifiche di eventi. NCache migliora ulteriormente la struttura dei dati della coda fornendo NCache-funzioni specifiche come Gruppi, Tags, Scadenza, Blocco, dipendenzeE altro ancora.

È possibile utilizzare le code in NCache per mantenere aggiornate le informazioni in fase di elaborazione. Ad esempio, gli ID delle candidature dei candidati per un'azienda possono essere memorizzati in una coda. Poiché la coda segue la logica FIFO (First-In, First-Out), il primo candidato a candidarsi verrà intervistato per primo, e così via. Inoltre, l'azienda può specificare un gruppo per una coda di persone che si sono candidate per posizioni amministrative.

NCache Comportamento della coda distribuita

  • Una coda può essere di qualsiasi tipo primitivo o oggetto personalizzato.
  • Code di CacheItem Le code annidate non sono ancora supportate.
  • Le code hanno un nome. Pertanto, è necessario fornire una chiave di cache univoca per ogni coda.
  • I valori nulli non sono supportati.
  • Sono supportati valori duplicati.

Prerequisiti

Prima di usare il NCache Per le API lato client, assicurarsi che siano soddisfatti i seguenti prerequisiti:

  • .NET
  • Java
  • Node.js
  • Installa i seguenti pacchetti NuGet nella tua applicazione client .NET:
    • Impresa: Alachisoft.NCache.Sdk
    • Open Source: Alachisoft.NCache.SDK open source
  • Includere i seguenti spazi dei nomi nell'applicazione:
    • Alachisoft.NCache.Cliente
    • Alachisoft.NCache.Eccezioni.di.runtime
    • Alachisoft.NCache.Tipi.dati.client
    • Alachisoft.NCache.Client.DataTypes.Collections
    • Alachisoft.NCache.Memorizzazione.della.cache
    • Alachisoft.NCache.Eventi.di.runtime
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: ICache, IDistributedQueue, IdataTypeManager, contiene, Copia a, ToArray, Peek, OttieniCoda, Annullamento della coda, Accodare, Accodamento in blocco, DequeueBulk, Crea coda, Notifica di registrazione, DataTypeDataNotificationRichiamata, Tipo di evento, DataTypeEventDataFilter, bloccare, Sbloccare, DataType Manager, DataTypeEventArg.
  • Aggiungi le seguenti dipendenze Maven per la tua applicazione client Java in pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise-->
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Importa i seguenti pacchetti nell'applicazione client Java:
    • importare com.alachisoft.ncache.client.*;
    • importare com.alachisoft.ncache.runtime.eccezione.*;
    • importare com.alachisoft.ncache.client.datastructures.*;
    • importare com.alachisoft.ncache.runtime.events.*;
    • importare com.alachisoft.ncache.runtime.dependencies.*;
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, Coda distribuita, creaCoda, getQueue, bloccare, sbloccare, Tipo di evento, getEventType, addChangeListener, getDataStructuresManager, onDataStructureChanged, DataTypeEventDataFilter, DataStructureDataChangeListener, DataStructureEventArg, getCollectionItem, copia a, sbirciare, adArray.
  • Installa e includi il seguente modulo nella tua applicazione client Node.js:

    • Impresa: client ncache
  • Includi la seguente classe nella tua applicazione:

    • Cache
    • Gestore struttura dati
    • Coda distribuita
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, Coda distribuita, getDataStructuresManager, creaCoda, aggiungere, getQueue, contiene, copia a, adArray, sbirciare, rimuovere, Tipo di evento, DataStructureDataChangeListener, addChangeListener, DataTypeEventDataFilter, DataStructureEventArg, getEventType, getCollectionItem.

Come creare una coda e aggiungere dati

Il seguente esempio di codice mostra come creare una coda di Candidato digitare nella cache in base alla chiave della cache CandidateQueue e come gli elementi vengono aggiunti alla coda.

Consiglio

Puoi anche configurare gli attributi ricercabili come Gruppi/Tag/Tag con nome e attributi di invalidamento come scadenza/eliminazione/dipendenza durante la creazione di una struttura dati.

  • .NET
  • Java
  • Node.js
try
{
  // Precondition: Cache is already 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);
  }
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
    {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    }
    else if (ex.ErrorCode == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES)
    {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    }
    else
    {
        // NCache specific exception
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try
{
  // Precondition: Cache is already 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);
  }
}
catch (OperationFailedException ex) 
{
    if (ex.getErrorCode() == NCacheErrorCodes.KEY_ALREADY_EXISTS) {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    } else if (ex.getErrorCode() == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES) {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    } else {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
} 
catch (Exception ex) 
{
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try
{
  // This is an async method
  // Precondition: Cache is already 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);
  }
}
catch (error) {
  // Handle errors
}

Come creare una coda e aggiungere dati in blocco

Se vuoi aggiungere più elementi in una singola chiamata, puoi utilizzare EnqueueBulk metodo. Il seguente esempio di codice mostra come una coda di Candidato il tipo può essere creato nella cache rispetto alla chiave della cache CandidateQueue e come più elementi possono essere aggiunti alla coda in blocco.

Note:

Migliori EnqueueBulk Il metodo garantisce che gli elementi vengano aggiunti nello stesso ordine in cui appaiono nell'elenco fornito.

  • .NET
// Precondition: Cache is already 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();

// Add a list of candidates to the queue
queue.EnqueueBulk(candidates);

Se si verifica un errore durante l'aggiunta di un elemento durante la EnqueueBulk operazione, l'intero processo viene annullato. L'utente avrà tutti gli elementi in coda oppure verrà generata un'eccezione, senza alcun elemento aggiunto.

Come recuperare ed eseguire altri metodi sulla coda

Il seguente esempio di codice recupera una coda dalla cache utilizzando GetQueue metodo e quindi controlla se un elemento esiste nella coda utilizzando il Contains metodo. Recupera un elemento dall'inizio della coda senza rimuoverlo utilizzando il Peek metodo. È possibile copiare l'intera coda di origine nell'array di destinazione utilizzando il metodo CopyTo metodo e convertirlo in un array unidimensionale utilizzando il ToArray metodo.

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// 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 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.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 ID
Candidate candidate = getCandidateByID(1002);

// Check whether Queue contains the 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(new Candidate[0]);

// Get an item from the beginning of the queue without removing it
Candidate firstCandidate = retrievedQueue.peek();
// Precondition: Cache is already connected
// This is an async method

// 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 ID
var candidate = this.getCandidateByID(1002);

// Check whether Queue contains the particular candidate or not
if (retrievedQueue.contains(candidate))
{
// Candidate exists with this ID
}

// List of candidates
var candidates = await retrievedQueue.toArray();

// Get an item from the beginning of the queue without removing it
var firstCandidate = await retrievedQueue.peek();

Come rimuovere gli elementi dalla coda

Gli elementi possono essere rimossi dalla coda in modalità FIFO. Il seguente esempio di codice rimuove il primo candidato dalla coda.

Consiglio

Per rimuovere l'intera coda dalla cache, fare riferimento a Rimuovere le strutture di dati dalla cache .

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Remove the first item of the queue
retrievedQueue.Dequeue();
// Precondition: Cache is already connected

// Queue with this key already exists in cache
String key = "CandidateQueue";
DistributedQueue<Candidate> retrievedQueue = cache.getDataStructuresManager().getQueue(key, Candidate.class);

// Remove the first item of the queue
retrievedQueue.remove();
// Precondition: Cache is already connected

// This is an async method
// 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 the first item of the queue
await retrievedQueue.remove();
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.

Come rimuovere i dati in blocco

Se vuoi rimuovere più elementi in una singola chiamata, puoi utilizzare DequeueBulk metodo. Il DequeueBulk il metodo richiede a maxItems Parametro che specifica il numero massimo di elementi da rimuovere dalla coda. Se la coda contiene meno elementi del numero specificato, verranno rimossi dalla coda solo gli elementi disponibili. Ad esempio, se si specifica 10 ma sono presenti solo 7 elementi, tutti e 7 gli elementi verranno rimossi dalla coda. Il valore predefinito per il numero massimo di elementi è 10.

Il seguente esempio di codice mostra come recuperare la coda di Candidato digitare utilizzando la chiave cache CandidateQueue e come più elementi possono essere rimossi dalla coda in blocco.

Note:

Migliori DequeueBulk Il metodo garantisce che gli elementi vengano rimossi dalla coda nello stesso ordine in cui sono stati aggiunti, fino al numero specificato.

Avvertenza

Quando si utilizza la DequeueBulk Con questo metodo, si consiglia di estrarre dalla coda solo il numero di elementi necessari per l'elaborazione in quel momento. Estrarre dalla coda un numero di elementi superiore al necessario può aumentare i tempi di elaborazione, poiché ogni operazione comporta un proprio costo di elaborazione, soprattutto se la coda contiene una grande quantità di dati.

  • .NET
// Precondition: Cache is already connected

// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);

// Remove at most the first 10 items in the Queue
IList<Candidate> dequeuedItems = retrievedQueue.DequeueBulk(10);
Note:

Se la coda è vuota durante la DequeueBulk operazione, verrà generata un'eccezione.

Simile a EnqueueBulk, se si verifica un errore durante la rimozione di un elemento durante la DequeueBulk operazione, l'intero processo viene annullato. L'utente riceverà tutti gli elementi richiesti oppure verrà generata un'eccezione, senza restituzione di alcun elemento.

Registrazione delle notifiche degli eventi nelle code

È possibile registrare eventi cache, eventi basati su chiave ed eventi di struttura dati su una struttura dati come una coda. Per maggiori dettagli, fare riferimento a comportamento in termini di funzionalità.

Come registrare un evento nella coda creata

I seguenti esempi di codice registrano le notifiche degli eventi della struttura dati sulla coda. L'esempio .NET registra ItemAdded, ItemUpdatede ItemRemoved eventi, mentre gli esempi Java e Node.js registrano gli eventi ItemAdded e ItemRemoved. La creazione di una coda attiva un ItemAdded evento a livello di cache, mentre l'aggiunta di un elemento a una coda esistente attiva un ItemAdded evento della struttura dati e un ItemUpdated Evento a livello di cache.

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already connected

// 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.ItemRemoved);

// Register ItemAdded and ItemRemoved events on the created Queue
// dataChangeListener is the specified callback method
queue.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations
// Precondition: Cache is already connected

// This is an async method
// Unique cache key for the Queue
var key = "CandidateQueue";

// Create Queue of candidate type
var manager = await this.cache.getDataStructuresManager();
var queue = await manager.createQueue(key, ncache.JsonDataType.Object);

// Create EnumSet of event types
// Update EventType is not supported
var enumSet = [
ncache.EventType.ItemAdded,
ncache.EventType.ItemRemoved
];

queue.addChangeListener(
this.dataStructureListener, // Make sure this is initialized
enumSet,
ncache.DataTypeEventDataFilter.Data
);

// Perform operations

Come specificare il callback per la notifica degli eventi

Il seguente esempio di codice mostra come specificare un metodo di callback per ricevere notifiche per diversi eventi, come quando un elemento viene aggiunto, aggiornato o rimosso da una raccolta. Gestire questi eventi consente di attivare azioni specifiche in risposta a modifiche nella cache.

  • .NET
  • Java
  • Node.js
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;
    }
}
public 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 ItemRemoved:
                //Item has been removed from the collection
            break;
        }
    }
};
// Update event is not supported for this dataType
onDataStructureChanged(collectionName, eventArg)
{
  switch (eventArg.getEventType())
  {
    case ncache.EventType.ItemAdded:
      // Item has been added to the collection
      break;

    case ncache.EventType.ItemRemoved:
      // Item has been removed from the collection
      break;
  }
}

Come bloccare le code

Le code possono essere bloccate e sbloccate in modo esplicito per garantire la coerenza dei dati. Il seguente esempio di codice crea una coda e la blocca per un periodo di 10 secondi utilizzando bloccare e poi lo sblocca usando Sbloccare.

  • .NET
  • Java
// Precondition: Cache is already connected

// 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();
// Precondition: 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();

Risorse addizionali

NCache fornisce un'applicazione di esempio per la struttura dati della coda su GitHub.

Vedere anche

.NETTO: Alachisoft.NCache.Tipi.dati.client spazio dei nomi.
Giava: com.alachisoft.ncache.client.datastructures spazio dei nomi.
Node.js: Coda distribuita classe.

Contattaci

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
E-MAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Confronto edizione
  • NCache Architettura
  • Parametri di riferimento
Scaricare
Prezzi
Prova Parco giochi

Distribuzioni
  • Cloud (SaaS e software)
  • On-Locale
  • kubernetes
  • docker
Casi d'uso tecnici
  • Sessioni ASP.NET
  • Sessioni ASP.NET Core
  • Messaggistica Pub/Sub
  • SignalR in tempo reale per ASP.NET
  • Internet of Things (IoT)
  • Database NoSQL
  • Streaming Processing
  • Microservices
Risorse
  • Articoli di riviste
  • Articoli di terze parti
  • Articoli
  • Video
  • Fogli bianchi
  • Spettacoli
  • trattativa
  • Blog
  • Docs
Casi di studio dei clienti
  • Testimonianze
  • Clienti
Assistenza
  • Pianificare un demo
  • Forum (Google Gruppi)
  • Consigli
Azienda
  • Leadership
  • Partner
  • News
  • Eventi
  • Lavora con noi
Contattaci

  • IngleseCinese (semplificato)FranceseTedescoItalianoGiapponeseCoreanoPortogheseCorsi

  • Contattaci
  •  
  • Mappa del sito
  •  
  • Termini d’uso
  •  
  • Informativa privacy
© Copyright Alachisoft 2002 - . Tutti i diritti riservati. NCache è un marchio registrato di Diyatech Corp.
Torna in alto