Comportamento do contador e uso em cache
Um contador é uma estrutura de dados única de valor longo armazenada no cache. Você pode aumentar, diminuir, bloquear e registrar eventos nele. Por exemplo, um contador pode ser usado para armazenar as visualizações sempre que um vídeo é visualizado em um site de mídia social. Ele também pode ser usado para armazenar assinaturas em um site onde as pessoas podem se inscrever ou cancelar.
NCache aumenta ainda mais este contador, fornecendo NCache- recursos específicos, como Grupos, Tags, Expiration, Bloqueio, Dependências, e mais. Por exemplo, você pode especificar um contador para o grupo Detalhes da assinatura que pode conter objetos do cliente, bem como o contador de assinaturas.
Comportamento
- Nulo não é um tipo de valor com suporte.
- Os contadores são nomeados. Portanto, você precisa fornecer uma chave de cache exclusiva para um contador.
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, Contador, IDataTypeManager, CriarContador, Definir valor, Incremento, Incrementar por, Decrementar, Decrementar por, ObterContador, ICollectionManager, 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, Contador, getDataStructuresManager, criarContador, obterContador, valor definido, incremento, incrementar por, decremento, diminuir por, Eventtype, getEventType, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, DataTypeEventDataFilter, getCollectionItem, trancar, 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, Contador, DataStructureManager, getDataStructuresManager, criarContador, obterContador, valor definido, incremento, incrementar por, decremento, diminuir por, 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, Contador, DataStructureManager, get_data_estruturas_manager, criar_contador, get_counter, incremento, get_event_type, DataTypeEventDataFilter, EventDataFilter.
Criar contador
O exemplo de código a seguir mostra como um contador pode ser criado no cache usando CreateCounter
contra a chave de cache Contador de assinaturas.
// 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)
Buscar e atualizar o valor do contador
Você pode atualizar o valor de um contador após sua criação. O exemplo de código a seguir busca um contador do cache usando GetCounter
e define seu valor para outro valor, usando SetValue
. Em seguida, ele incrementa seu valor usando Increment
or IncrementBy
e diminui seu valor usando 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
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 contadores
Você pode registrar eventos de cache, eventos baseados em chave e eventos de estrutura de dados em uma estrutura de dados, como um contador. 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
no balcão no cache. Uma vez que um contador é criado no cache, um ItemAdded
evento em nível de cache é acionado. No entanto, uma vez que um item é adicionado ao contador, um ItemAdded
evento de estrutura de dados é acionado e um ItemUpdated
evento de nível de cache é acionado.
Registrar evento no contador criado
// 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
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)
Contador de bloqueio
Os contadores podem ser bloqueados e desbloqueados explicitamente para garantir a consistência dos dados. O exemplo de código a seguir cria um contador e o bloqueia por um período de 10 segundos usando Travar e, em seguida, desbloqueia usando Destravar.
// 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();
Recursos adicionais
NCache fornece um aplicativo de exemplo para a estrutura de dados do contador 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: Contador classe.
Pitão: ncache.client.dataestruturas classe.