Comportamento e utilizzo del contatore nella cache
Un contatore è una singola struttura dati a valore lungo archiviata nella cache. È possibile incrementare, decrementare, bloccare e registrare eventi rispetto ad esso. Ad esempio, è possibile utilizzare un contatore per memorizzare le visualizzazioni ogni volta che un video viene visualizzato su un sito di social media. Può anche essere utilizzato per archiviare abbonamenti su un sito Web in cui le persone possono iscriversi o annullare l'iscrizione.
NCache migliora ulteriormente questo contatore fornendo NCache-funzioni specifiche come ATTIVITA' E GRUPPI, tag, 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
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- 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.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- 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.
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Per i dettagli dell'API, fare riferimento a: Cache, contatore, Gestore struttura dati, getDataStructuresManager, creareContatore, getContatore, valore impostato, incremento, incremento di, decremento, decremento di, Tipo di evento , DataStructureDataChangeListener, addChangeListener, 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.
// Precondition: Cache must be 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);
// Precondition: Cache must be 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);
// This is an async method
// Precondition: Cache must be 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);
# Precondition: Cache must be connected
# Specify unique cache key for counter
key = "SubscriptionCounter"
# Set initial value of counter
initial_value = 15
# Create counter
manager = cache.get_data_structures_manager()
counter = manager.create_counter(key, initial_value)
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
.
// 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 number of 10
newValue = retrievedCounter.IncrementBy(10);
// Decrement value by number of 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 number of 10
newValue = retrievedCounter.incrementBy(10);
// Decrement value by number of 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 number of 10
newValue = retrievedCounter.incrementBy(10);
// Decrement value by number of 5
newValue = retrievedCounter.decrementBy(5);
# Precondition: Cache is already connected
# Unique key for counter
key = "SubscriptionCounter"
# Get counter against key
manager = cache.get_data_structures_manager()
retrieved_counter = manager.get_counter(key)
# Increment value of retrievedCounter on new subscription
retrieved_counter.increment()
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
ed ItemUpdated
così come registra un evento per ItemAdded
ed ItemUpdated
sul bancone nella cache. Una volta creato un contatore nella cache, an ItemAdded
viene generato un evento a livello di cache. Tuttavia, una volta aggiunto un oggetto al contatore, an ItemAdded
viene attivato l'evento della struttura dati e un ItemUpdated
l'evento a livello di cache viene attivato.
Registra evento sul contatore creato
// 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 |
EventType.ItemUpdated | EventType.ItemRemoved,
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 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);
counter.addChangeListener(dataChangeListener, 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 counter = await this.cache.getDataStructuresManager().createCounter(key, initialValue);
// 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 = dataStructureListener.onDataStructureChanged(
collectionName,
args
);
counter.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 counter
key = "SubscriptionCounter"
# Set initial value of counter
initial_value = 15
# Create counter
counter = cache.get_data_structures_manager().create_counter(key, initial_value)
# Register ItemAdded, ItemUpdated, ItemRemoved events on hashset created
events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]
counter.add_change_listener(datastructure_callback_function, events_list, ncache.DataTypeEventDataFilter.DATA)
# Perform operations
Specificare la richiamata per la notifica dell'evento
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)
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.
// 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();
// Preconditions: 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.strutture.dati.client spazio dei nomi.
Node.js: contatore classe.
Pitone: ncache.strutture.dati.client classe.