Imposta il comportamento e l'utilizzo nella cache
Un HashSet è una struttura dati non ordinata che non contiene valori duplicati. Ad esempio, un HashSet può essere utilizzato per memorizzare l'ID utente di tutti gli utenti che accedono a un sito di e-commerce in un dato giorno. Se l'utente effettua nuovamente l'accesso, l'ID non viene memorizzato, poiché non sono ammessi valori duplicati. A differenza di un HashSet locale, NCache L'implementazione consente di eseguire operazioni di set (unione, intersezione, differenza) direttamente sul cluster di cache senza dover recuperare la raccolta completa sul client, garantendo prestazioni elevate per set di dati di grandi dimensioni.
NCache migliora ulteriormente HashSet fornendo NCache caratteristiche specifiche come Gruppi, Tags, Scadenza, Blocco, dipendenzeE altro ancora.
Comportamento
- Un HashSet può essere solo di tipo primitivo.
- Gli hashset sono denominati. Pertanto, è necessario fornire una chiave cache univoca per ogni HashSet.
- Null non è un tipo di valore supportato.
- I valori duplicati non sono supportati.
Prerequisiti
Prima di usare il NCache Per le API lato client, assicurarsi che siano soddisfatti i seguenti prerequisiti:
- 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:
- La cache deve essere in esecuzione.
- Assicurati che i dati aggiunti lo siano serializzabile.
- Per i dettagli dell'API, fare riferimento a: ICache, IDistributedHashSet, IdataTypeManager, CreaHashSet, OttieniHashSet, StoreUnion, StoreIntersezione, MemorizzaDifferenza, Rimuovere, Notifica di registrazione, DataTypeDataNotificationRichiamata, Tipo di evento, DataTypeEventDataFilter, bloccare, Sbloccare, DataType Manager, DataTypeEventArg.
Crea HashSet e aggiungi dati
Note:
Un insieme non può contenere valori duplicati.
L'esempio di codice seguente crea due HashSet di tipo int nella cache utilizzando CreateHashSet per gli utenti che accedono lunedì e martedì. Quindi aggiunge i dati a questi due HashSet.
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.
try
{
// Precondition: Cache is already connected
// Create unique keys for HashSets
string mondayUsersKey = "MondayUsers";
string tuesdayUsersKey = "TuesdayUsers";
// Create HashSets of int type
IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.CreateHashSet<int>(mondayUsersKey);
// Add user IDs for Monday
userSetMonday.Add(1223);
userSetMonday.Add(34564);
userSetMonday.Add(3564);
IDistributedHashSet<int> userSetTuesday = cache.DataTypeManager.CreateHashSet<int>(tuesdayUsersKey);
// Add userIDs for Tuesday
userSetTuesday.Add(4545);
userSetTuesday.Add(34564);
userSetTuesday.Add(3564);
userSetTuesday.Add(7879);
}
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
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
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.
Esegui unione e intersezione su HashSet
NCache fornisce anche supporto per operazioni HashSet native come Union, Intersectione Difference. L'esempio di codice seguente crea tre HashSet di tipo int che archiviano il file Union, Intersectione Difference dei due HashSet utenteSetMonday and utenteSetTuesday creato nell'esempio precedente:
// Precondition: Cache is already connected
// Create unique keys for HashSets
string totalUsersKey = "TotalUsers";
string weeklyUsersKey = "WeeklyUsers";
string differenceKey = "Difference";
// Create HashSets of int type
IDistributedHashSet<int> userSetTotal = cache.DataTypeManager.CreateHashSet<int>(totalUsersKey);
IDistributedHashSet<int> userSetWeekly = cache.DataTypeManager.CreateHashSet<int>(weeklyUsersKey);
IDistributedHashSet<int> userSetDifference = cache.DataTypeManager.CreateHashSet<int>(differenceKey);
// userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
userSetMonday.StoreUnion(totalUsersKey, tuesdayUsersKey);
// userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
userSetMonday.StoreIntersection(weeklyUsersKey, tuesdayUsersKey);
// userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
userSetMonday.StoreDifference(differenceKey, tuesdayUsersKey);
Recupera HashSet dalla cache
Puoi recuperare un HashSet dalla cache usando GetHashSet che accetta una chiave cache come parametro. Questa chiave è il nome dell'HashSet, che viene specificato durante la creazione dell'HashSet.
Avvertenza
Se l'elemento recuperato non è di tipo HashSet, a Type mismatch viene generata un'eccezione.
// Precondition: Cache is already connected
// HashSet with this key already exists in cache
string key = "ProductIDSet";
// Get HashSet and show items of HashSet
IDistributedHashSet<int> retrievedHashSet = cache.DataTypeManager.GetHashSet<int>(key);
if (retrievedHashSet != null)
{
foreach (var item in retrievedHashSet)
{
// Perform operations
}
}
else
{
// HashSet does not exist
}
Rimuovi elementi da HashSet
Gli elementi possono essere rimossi da un HashSet specificando l'elemento stesso o in modo casuale. L'esempio di codice seguente rimuove gli utenti di lunedì dagli utenti settimanali HashSet (che sono già stati aggiunti alla cache).
Consiglio
Per rimuovere l'intero set dalla cache, fare riferimento a Rimuovere le strutture di dati dalla cache .
// Precondition: Cache is already connected
// Get existing HashSets
string userIDMondayKey = "UserIDMonday";
string userIDWeeklyKey = "UserIDWeekly";
IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.GetHashSet<int>(userIDMondayKey);
IDistributedHashSet<int> usersWeekly = cache.DataTypeManager.GetHashSet<int>(userIDWeeklyKey);
// Remove users of Monday from Weekly HashSet
var removedItem = usersWeekly.Remove(userSetMonday);
Notifiche di eventi su HashSet
È possibile registrare eventi cache, eventi basati su chiavi ed eventi struttura dati su una struttura dati come un HashSet. Per il comportamento, fare riferimento a caratteristica comportamento saggio.
I seguenti esempi di codice registrano le notifiche degli eventi della struttura dati su HashSet. L'esempio .NET registra ItemAdded, ItemUpdatede ItemRemoved eventi, mentre l'esempio Java registra ItemAdded and ItemRemoved eventi. La creazione di un HashSet attiva un ItemAdded evento a livello di cache. L'aggiunta di un elemento a un HashSet esistente attiva un ItemAdded evento della struttura dati e un ItemUpdated Evento a livello di cache.
Registra l'evento su HashSet creato
// Precondition: Cache is already connected
// Unique cache key for hashset
string key = "UserIDMonday";
// Create hashset
IDistributedHashSet<int> hashset = cache.DataTypeManager.CreateHashSet<int>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on HashSet created
// DataTypeNotificationCallback is callback method specified
hashset.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
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;
}
}
Blocco hashset
Un HashSet può essere bloccato e sbloccato in modo esplicito per garantire la coerenza dei dati. L'esempio di codice seguente crea un HashSet e lo blocca per un periodo di 10 secondi utilizzando bloccare e poi lo sblocca usando Sbloccare.
// Precondition: Cache is already connected
// HashSet exists with key "UserIDMonday" Cache Key
string key = "UserIDMonday";
// Get HashSet
IDistributedHashSet<int> hashset = cache.DataTypeManager.GetHashSet<int>(key);
// Lock HashSet for 10 seconds
bool isLocked = hashset.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// HashSet is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// HashSet is not locked because either:
// HashSet is not present in the cache
// HashSet is already locked
}
hashset.Unlock();
Risorse addizionali
NCache fornisce un'applicazione di esempio per la struttura di dati HashSet GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Tipi.dati.client spazio dei nomi.
Giava: com.alachisoft.ncache.client.datastructures spazio dei nomi.