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

Comportamento e utilizzo del contatore nella cache

Un contatore è un struttura dati a valore lungo singolo memorizzato nella cache. È possibile incrementare, decrementare, bloccare e registrare eventi. Ad esempio, un contatore può essere utilizzato per memorizzare le visualizzazioni ogni volta che un video viene visualizzato su un sito di social media. Può anche essere utilizzato per memorizzare le iscrizioni a un sito web in cui gli utenti possono iscriversi o annullare l'iscrizione. NCache migliora ulteriormente questo contatore fornendo NCache-funzioni specifiche come Gruppi, Tags, Scadenza, Blocco, dipendenze, e altro ancora. Ad esempio, puoi specificare un contatore per il gruppo AbbonamentoDettagli che può contenere oggetti cliente oltre al contatore abbonamenti.

Comportamento

  • Null non è un tipo di valore supportato.
  • I contatori sono nominati. Pertanto, è necessario fornire una chiave cache univoca per un contatore.

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.Client.DataTypes.Contatore
    • 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, Contatore, IdataTypeManager, Crea contatore, Valore impostato, Incremento, Incremento di, diminuzione, Decrementa, Ottieni contatore, ICollection Manager, 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, contatore, getDataStructuresManager, creareContatore, getContatore, valore impostato, incremento, incremento di, decremento, decremento di, Tipo di evento, getEventType, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, DataTypeEventDataFilter, getCollectionItem, bloccare, sbloccare, addChangeListener.
  • 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
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, contatore, creareContatore, decremento, decremento di, getContatore, incremento, valore impostato, incremento di, addChangeListener, DataStructureDataChangeListener, Tipo di evento, DataTypeEventDataFilter, DataStructureEventArg, getEventType, getCollectionItem.

Crea contatore

L'esempio di codice seguente mostra come è possibile creare un contatore nella cache utilizzando CreateCounter contro la chiave della cache AbbonamentoContatore.

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 counter
  string key = "SubscriptionCounter";

  // Set initial value of counter
  long initialValue = 15;

  // Create counter
  ICounter counter = cache.DataTypeManager.CreateCounter(key, initialValue);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
    {
        // The specified key already exists in the cache,
        // Either remove the existing object from the cache
        // Or specify another key
    }
    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 counter
  String key = "SubscriptionCounter";

  // Set initial value of counter
  long initialValue = 15;

  // Create counter
  Counter counter = cache.getDataStructuresManager().createCounter(key, initialValue);
}
catch (OperationFailedException ex) 
{
    // NCache specific errors
    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 {
        // NCache specific exception
        // 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 counter
  var key = "SubscriptionCounter";

  // Set initial value of counter
  var initialValue = 15;

  // Create counter
  var manager = await this.cache.getDataStructuresManager();
  var counter = await manager.createCounter(key, initialValue);
}
catch (error) {
  // Handle errors
}

Recupera e aggiorna il valore del contatore

Puoi aggiornare il valore di un contatore dopo la sua creazione. L'esempio di codice seguente recupera un contatore dalla cache utilizzando GetCounter e imposta il suo valore su un altro valore, utilizzando SetValue. Quindi incrementa il suo valore utilizzando Increment or IncrementBy e ne decrementa il valore utilizzando Decrement or DecrementBy.

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

// Unique key for counter
string key = "SubscriptionCounter";

// Get counter against key
ICounter retrievedCounter = cache.DataTypeManager.GetCounter(key);

// Set value of counter to 100
retrievedCounter.SetValue(100);

// Increment value
long newValue =  retrievedCounter.Increment();

// Decrement value
newValue =  retrievedCounter.Decrement();

// Increment value by 10
newValue =  retrievedCounter.IncrementBy(10);

// Decrement value by 5
newValue =  retrievedCounter.DecrementBy(5);
// Precondition: Cache is already connected

// Unique key for counter
String key = "SubscriptionCounter";

// Get counter against key
Counter retrievedCounter = cache.getDataStructuresManager().getCounter(key);

// Set Value of counter to 100
retrievedCounter.setValue(100);

// Increment value
long newValue =  retrievedCounter.increment();

// Decrement value
newValue =  retrievedCounter.decrement();

// Increment value by 10
newValue =  retrievedCounter.incrementBy(10);

// Decrement value by 5
newValue =  retrievedCounter.decrementBy(5);
// This is an async method
// Precondition: Cache is already connected

// Unique key for counter
var key = "SubscriptionCounter";

// Get counter against key
var manager = await this.cache.getDataStructuresManager();
var retrievedCounter = await manager.getCounter(key);

// Set Value of counter to 100
retrievedCounter.setValue(100);

// Increment value
var newValue =  retrievedCounter.increment();

// Decrement value
newValue =  retrievedCounter.decrement();

// Increment value by 10
newValue =  retrievedCounter.incrementBy(10);

// Decrement value by 5
newValue =  retrievedCounter.decrementBy(5);
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.

Notifiche di eventi sui contatori

È possibile registrare eventi cache, eventi basati su chiavi ed eventi struttura dati su una struttura dati come un contatore. Per il comportamento, fare riferimento a caratteristica comportamento saggio.

L'esempio di codice seguente registra un evento cache di ItemAdded and ItemUpdated così come registra un evento per ItemAdded and ItemUpdated sul contatore nella cache. La creazione di un contatore attiva un ItemAdded evento a livello di cache. Quando il valore del contatore viene modificato, un ItemUpdated evento della struttura dati e un ItemUpdated Vengono attivati ​​gli eventi a livello di cache.

Registra evento sul contatore creato

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

// Unique cache key for counter
string key = "SubscriptionCounter";

// Set initial value of counter
long initialValue = 15;

// Create counter
ICounter counter = cache.DataTypeManager.CreateCounter(key, initialValue);

// Register ItemAdded, ItemUpdated, ItemRemoved events on counter created
// DataTypeNotificationCallback is callback method specified
counter.RegisterNotification(DataTypeDataNotificationCallback, 
        EventType.ItemAdded,
        DataTypeEventDataFilter.Data);

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

// Unique cache key for counter
String key = "SubscriptionCounter";

// Set initial value of counter
long initialValue = 15;

// Create counter
Counter counter = cache.getDataStructuresManager().createCounter(key, initialValue);

// Create EnumSet of event type ItemUpdated
// Registration for Add and Remove Event type is not supported for Counters
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemUpdated);


counter.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations
// This is an async method
// Precondition: Cache is already connected

 // Unique cache key for counter
var key = "SubscriptionCounter";

// Set initial value of counter
var initialValue = 15;

// Create counter
var manager = await this.cache.getDataStructuresManager();
var counter = await manager.createCounter(key, initialValue);

// Create EnumSet of event types
var enumSet = [
    ncache.EventType.ItemUpdated,
];

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

Specificare la richiamata per la notifica dell'evento

  • .NET
  • Java
  • Node.js
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
    if (collectionEventArgs.EventType == EventType.ItemUpdated)
    {
        if (collectionEventArgs.CollectionItem != null)
        {
            // Counter value has been updated
            // Perform operations
        }
    }
}
DataStructureDataChangeListener dataStructureListener = new DataStructureDataChangeListener() {
    @Override
    public void onDataStructureChanged(String collection, DataStructureEventArg dataStructureEventArg) {
        switch (dataStructureEventArg.getEventType()) {
            case ItemUpdated:
                if (dataStructureEventArg.getCollectionItem() != null) {
                    //Item has been updated in the collection
                    // perform operations
                }
            break;

        }
    }
};
// Add and Remove event is not supported for this dataType
onDataStructureChanged(collectionName, eventArg) 
{
  switch (eventArg.getEventType()) 
  {
    case ncache.EventType.ItemUpdated:
      if (eventArg.getCollectionItem() != null) 
      {
        // Item has been updated in the collection
        // Perform operations
      }
      break;
  }
}

Contatore di blocco

I contatori possono essere bloccati e sbloccati in modo esplicito per garantire la coerenza dei dati. L'esempio di codice seguente crea un contatore e lo blocca per un periodo di 10 secondi utilizzando bloccare e poi lo sblocca usando Sbloccare.

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

// Counter exists with key "SubscriptionCounter"
// Cache Key
string key = "SubscriptionCounter";

// Get counter against key
ICounter counter = cache.DataTypeManager.GetCounter(key);

// Lock counter for 10 seconds
bool isLocked = counter.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
    // Counter is successfully locked for 10 seconds
    // Unless explicitly unlocked
}
else
{
    // Counter is not locked because either:
    // Counter is not present in the cache
    // Counter is already locked
}

counter.Unlock();
// Precondition: Cache is already connected

// Counter exists with key "SubscriptionCounter"
// Cache Key
String key = "SubscriptionCounter";

// Get counter against key
Counter counter = cache.getDataStructuresManager().getCounter(key);

// Lock counter for 10 seconds
boolean isLocked = counter.lock(TimeSpan.FromSeconds(10));
if (isLocked) 
{
    // Counter is successfully locked for 10 seconds
    // Unless explicitly unlocked
} else 
{
    // Counter is not locked because either:
    // Counter is not present in the cache
    // Counter is already locked
}
counter.unlock();

Risorse addizionali

NCache fornisce un'applicazione di esempio per la struttura dei dati del contatore GitHub.

Vedere anche

.NETTO: Alachisoft.NCache.Tipi.dati.client spazio dei nomi.
Giava: com.alachisoft.ncache.client.datastructures spazio dei nomi.
Node.js: contatore 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