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

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:

  • .NET
  • Java
  • 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, IDistributedHashSet, IdataTypeManager, CreaHashSet, OttieniHashSet, StoreUnion, StoreIntersezione, MemorizzaDifferenza, Rimuovere, 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, HashSet distribuito, getDataStructuresManager, createHashSet, getHashSet, negozioUnion, storeIntersezione, storeDifference, Tipo di evento, getEventType, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, DataTypeEventDataFilter, getCollectionItem, bloccare, sbloccare, addChangeListener, rimuovere.

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.

  • .NET
  • Java
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
}
try
{
  // Precondition: Cache is already connected

  // Create unique keys for HashSets
  String mondayUsersKey = "MondayUsers";
  String tuesdayUsersKey = "TuesdayUsers";

  // Create HashSets of int type
  DistributedHashSet userSetMonday = cache.getDataStructuresManager().createHashSet(mondayUsersKey, Integer.class);

  // Add user IDs for Monday
  userSetMonday.add(1223);
  userSetMonday.add(34564);
  userSetMonday.add(3564);
  DistributedHashSet userSetTuesday = cache.getDataStructuresManager().createHashSet(tuesdayUsersKey, Integer.class);

  // Add userIDs for Tuesday
  userSetTuesday.add(4545);
  userSetTuesday.add(34564);
  userSetTuesday.add(3564);
  userSetTuesday.add(7879);
}
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
}
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:

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

// Create unique keys for HashSets
String totalUsersKey = "TotalUsers";
String weeklyUsersKey = "WeeklyUsers";
String differenceKey = "Difference";

// Create HashSets of int type
DistributedHashSet userSetTotal = cache.getDataStructuresManager().createHashSet(totalUsersKey, Integer.class);
DistributedHashSet userSetWeekly = cache.getDataStructuresManager().createHashSet(weeklyUsersKey, Integer.class);
DistributedHashSet userSetDifference = cache.getDataStructuresManager().createHashSet(differenceKey, Integer.class);

// 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.

  • .NET
  • Java
// 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
}
// Precondition: Cache is already connected

// HashSet with this key already exists in cache
String key = "ProductIDSet";

// Get HashSet and show items of HashSet
DistributedHashSet retrievedHashSet = cache.getDataStructuresManager().getHashSet(key, Integer.class);
if (retrievedHashSet != null) 
{
    for (var item : 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 .

  • .NET
  • Java
// 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);
// Precondition: Cache must be connected

// Get existing HashSets
String userIDMondayKey = "UserIDMonday";
String userIDWeeklyKey = "UserIDWeekly";
DistributedHashSet userSetMonday = cache.getDataStructuresManager().getHashSet(userIDMondayKey, Integer.class);
DistributedHashSet usersWeekly = cache.getDataStructuresManager().getHashSet(userIDWeeklyKey, Integer.class);

// 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

  • .NET
  • Java
// 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
// Precondition: Cache is already connected

// Unique cache key for hashset
String key = "UserIDMonday";

// Create HashSet
DistributedHashSet<Integer> hashSet = cache.getDataStructuresManager().createHashSet(key, Integer.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 HashSet created, ItemUpdated event is not supported for this data type
// dataChangeListener is the specified callback method
hashSet.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations

Specificare la richiamata per la notifica dell'evento

  • .NET
  • Java
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 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.

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

// HashSet exists with key "UserIDMonday" Cache Key
String key = "UserIDMonday";

// Get HashSet
DistributedHashSet hashset = cache.getDataStructuresManager().getHashSet(key, Integer.class);

// Lock HashSet for 10 seconds
boolean 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.

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