Strutture di dati distribuiti in NCache

NCache è una cache distribuita estremamente veloce e scalabile per .NET, Java, Node.jse Python applicazioni. NCache viene utilizzato dalle applicazioni server .NET ad alto numero di transazioni per la memorizzazione nella cache dei dati delle applicazioni, ASP.NET / ASP.NET Core archiviazione della sessione e Messaggistica Pub/Sub.

NCache offre Strutture di dati distribuiti che possono essere condivise tra più utenti. A differenza delle strutture locali che risiedono nell'heap dell'applicazione client, queste strutture sono ospitate nel Distributed Cache Cluster, riducendo la pressione sulla memoria locale e il sovraccarico della garbage collection. Tra queste, si annoverano:

Caratteristica Raccolte standard in corso NCache Strutture distribuite
Obbiettivo Vincolato al processo (heap locale) Cluster-Wide (risorsa di rete condivisa)
Ciclo di vita Perso durante il riavvio/riciclo dell'applicazione Indipendente dal ciclo di vita dell'applicazione
Disponibilità Singolo punto di errore (il processo) Alta disponibilità (tramite topologie di partizione/replica)
Consistenza Thread-safe solo all'interno di un singolo processo Coerenza garantita su più server

Le sezioni seguenti forniscono dettagli ed esempi di codice per le applicazioni .NET e Java.

 

Coda distribuita

A Coda distribuita implementa il IDistributedQueue<T> Interfaccia, che consente di creare una coda da condividere tra più applicazioni .NET e Java in esecuzione in un ambiente distribuito. Inoltre, la coda garantisce il mantenimento della sequenza in cui sono stati inseriti i dati. Tutte le applicazioni che recuperano dati dalla coda possono contare sul fatto che questa sequenza sia sempre corretta.

string cacheName = "demoCache";
string QueueName = "DistributedQueue:Customers";
  
// Initialize an instance of the cache to begin performing operations
ICache cache = CacheManager.GetCache(cacheName);
  
// Create a thread-safe distributed queue visible to all cluster nodes
IDistributedQueue<Customer> distQueue = 
cache.DataTypeManager.CreateQueue<Customer>(QueueName);
  
distQueue.Enqueue(new Customer {
	ContactName = "David Johnes", 
	CompanyName = "Lonesome Pine Restaurant"
});
String cacheName = "demoCache";
String queueName = "DistributedQueue:Customers";

// Initialize an instance of the cache to begin performing operations
Cache cache = CacheManager.getCache(cacheName);

// Create a thread-safe distributed queue visible to all cluster nodes
DistributedQueue<Customer> distQueue = cache.getDataStructuresManager().createQueue(queueName, Customer.class);

distQueue.add(new Customer("David Johnes", "Lonesome Pine Restaurant"));
distQueue.add(new Customer("Carlos Gonzalez", "LILA-Supermercado"));

Come puoi vedere sopra, una coda distribuita ti consente di aggiungere (accodare) elementi in una sequenza in modo da poterli rimuovere (eliminare dalla coda) in seguito nella stessa sequenza (FIFO). Ecco l'interfaccia della coda distribuita:

public interface IDistributedQueue<T> : IEnumerable<T>, IEnumerable, ICollection, IDistributedDataTypes, ILockable, INotifiable
  {
      void Clear();
      bool Contains(T item);
      void CopyTo(T[] array, int arrayIndex);
      T Dequeue();
      IList<T> DequeueBulk(int maxitems = 10);
      void Enqueue(T item);
      void EnqueueBulk(IList<T> items);
      T Peek();
      T[] ToArray();
  }
public interface DistributedQueue<T> extends Queue<T>, DistributedDataStructure, Notifiable {
    void clear();

    void copyTo(T[] var1, int var2);

    T peek();

    Object[] toArray();
}
 

HashSet distribuito

A HashSet distribuito Si comporta esattamente come la classe .NET HashSet, ma in modo condiviso per più applicazioni e utenti. Fornisce tutte le operazioni Set come:

  • - Nessun duplicato: nel set
  • - Impostare le operazioni: come Unione, Intersezione e Differenza

Essendo un HashSet condiviso da più applicazioni o utenti, diventa una potente struttura dati da utilizzare. Ecco un esempio di come utilizzarlo.

string cacheName = "demoCache";
string hashSetName = "DistributedHashSet:UniqueValueHashSet";

// Initialize an instance of the cache to begin performing operations:
ICache cache = CacheManager.GetCache(cacheName);

// Creating a distributed HashSet with absolute expiration
IDistributedHashSet<string> hashSet;
hashSet = cache.DataTypeManager.CreateHashSet<string>(hashSetName);

// Create data for HashSet
var daysOfWeek = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

// Add multiple entries to the HashSet
hashSet.AddRange(daysOfWeek);

// Since this entry already exists, no change to the HashSet is made by this call
hashSet.Add("Monday");
String cacheName = "demoCache";
String hashSetName = "DistributedHashSet:UniqueValueHashSet";

// Initialize an instance of the cache to begin performing operations:
Cache cache = CacheManager.getCache(cacheName);

// Creating a distributed HashSet with absolute expiration
DistributedHashSet<String> hashSet;
hashSet = cache.getDataStructuresManager().createHashSet(hashSetName, String.class);

// Add entries to the hashset
hashSet.add("Monday");
hashSet.add("Tuesday");
hashSet.add("Wednesday");
hashSet.add("Thursday");
hashSet.add("Friday");
hashSet.add("Saturday");
hashSet.add("Sunday");

// Since this entry already exists, no change to the hashset is made by this call
hashSet.add("Monday");

Come puoi vedere, quando aggiungi "lunedì" per la seconda volta, non viene aggiunto all'HashSet.

 

Dizionario distribuito

A Dizionario distribuito (IDistributedDictionary) funge da sostituto diretto della normale interfaccia .NET IDictionary, ma in modalità condivisa per più applicazioni e utenti. Fornisce tutte le operazioni del dizionario, come Aggiungi, Aggiorna, Rimuovi, Contiene e altro ancora.

Oltre alle normali funzionalità del dizionario, il dizionario distribuito offre la possibilità di far scadere gli elementi in base a NCache opzioni di scadenza come Scadenza assoluta and Scadenza scorrevole.

ICache cache = CacheManager.GetCache("demoCache");
string dictName = "DistributedDictionary:Customers";

IDistributedDictionary<string, Customer> dict = cache.DataTypeManager.GetDictionary<string, Customer>(dictName);

if (dict == null)
{
	DataTypeAttributes attributes = new DataTypeAttributes {
		Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 1, 0))
	};
	// Creating a distributed Dictionary with an absolute expiration of 1 minute
	dict = cache.DataTypeManager.CreateDictionary<string, Customer>(dictName, attributes);
}

Customer cust = new Customer
{	
	CustomerID = "customer1",
	ContactName = "David Johnes",
	CompanyName = "Lonesome Pine Restaurant",
	ContactNo = "(1) 408-354-9768",
	Address = "Silicon Valley, Santa Clara, California",
};
	   
dict.Add("customer1", cust);

Customer cachedCust;
bool fetched = dict.TryGetValue("customer1", out cachedCust);
String cacheName = "demoCache";
String dictName = "DistributedDictionary:Customers";
 
// Initialize an instance of the cache to begin performing operations
Cache cache = CacheManager.getCache(cacheName);

DistributedMap<String, Customer> dict = cache.getDataStructuresManager().createMap(dictName, Customer.class);

Customer customer = new Customer("David Johnes", "Lonesome Pine Restaurant", "Customer1", "(1) 408-354-9768");

dict.put("customer1", customer);
Customer cachedCustomer = dict.get("customer1");
 

Elenco distribuito

Elenco distribuito implementa pienamente il System.Collections.Generic.IList<T> interfaccia, consentendogli di fungere da sostituto diretto degli elenchi standard. La differenza principale è che è distribuito e può essere condiviso tra più applicazioni e processi. L'elenco distribuito è un elenco non ordinato ed è possibile aggiungere elementi alla fine dell'elenco tramite Inserisci () metodo o in qualsiasi luogo attraverso il Inserire() metodo fornendo un indice.

Di seguito è riportato un esempio di come utilizzare un elenco distribuito.

ICache cache = CacheManager.GetCache("demoCache");
string listName = "DistributedList:Customers";

IDistributedList<Customer> distList = cache.DataTypeManager.GetList<Customer>(listName);

if (distList == null)
{
	DataTypeAttributes attributes = new DataTypeAttributes {
		Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 1, 0))
	};

	// Creating Distributed List with absolute expiration of 1 minute
	distList = cache.DataTypeManager.CreateList<Customer>(listName, attributes);
}

Customer cust = new Customer
{
	CustomerID = "customer1",
	ContactName = "David Johnes",
	CompanyName = "Lonesome Pine Restaurant",
	ContactNo = "(1) 408-354-9768",
	Address = "Silicon Valley, Santa Clara, California",
};

distList.Add(cust);
Customer cachedCustomer = distList[0];
String cacheName = "demoCache";
String listName = "DistributedList:Customers";

// Initialize an instance of the cache to begin performing operations:
Cache cache = CacheManager.getCache(cacheName);

DistributedList distributedList = cache.getDataStructuresManager().createList(listName,   Customer.class);

Customer customer = new Customer("David Johnes", "Lonesome Pine Restaurant", "Customer1", "(1) 408-354-9768");

distributedList.add(customer);
Customer cachedCustomer = (Customer) distributedList.get(0);

Puoi anche rimuovere elementi dall'elenco, scorrere su di esso ed eseguire molte altre operazioni.

 

Contatore distribuito

Contatore distribuito è una potente struttura dati in NCache che consente di mantenere un contatore unico in un ambiente distribuito condiviso da più applicazioni. Questo ha molti usi e ti consente di sviluppare rapidamente applicazioni attorno ad esso. Di seguito è riportato un esempio:

ICache cache = CacheManager.GetCache("demoCache");
string counterName = "DistributedCounter:Customers";

ICounter counter = cache.DataTypeManager.GetCounter(counterName);
if (counter == null)
{
   DataTypeAttributes attributes = new DataTypeAttributes {
      Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 1, 0))
   };

   // Creating Distributed Counter with absolute expiration to modify cache properties of the Counter, provide an instance of DataTypeAttributes in the second parameter
   counter = cache.DataTypeManager.CreateCounter(counterName, attributes);
}

counter.SetValue(1000);
long newValue = counter.IncrementBy(5);
newValue = counter.Value;
newValue = counter.DecrementBy(2);
String cacheName = "demoCache";
String counterName = "DistributedCounter:Customers";

// Initialize an instance of the cache to begin performing operations
Cache cache = CacheManager.getCache(cacheName);

Counter counter = cache.getDataStructuresManager().createCounter(counterName);
counter.setValue(1000);
long newValue = counter.incrementBy(5);
newValue = counter.getValue();
newValue = counter.decrementBy(2);

Cosa fare dopo?

Domande frequenti (FAQ)

Sì. Le serrature scorrevoli portatili e i catenacci a superficie possono essere usati per mettere in sicurezza una porta a scomparsa dall'esterno. Alcuni kit con catena di sicurezza consentono anche il bloccaggio esterno con chiave o manopola girevole. NCache Garantisce la sicurezza dei thread nell'intero cluster. Utilizza il blocco distribuito interno per gestire la concorrenza, assicurando che gli aggiornamenti simultanei da più applicazioni non causino corruzione dei dati o condizioni di competizione.

Un dizionario distribuito è condiviso tra processi e server, mentre un dizionario standard esiste solo nella memoria locale di una singola applicazione. Inoltre, NCache supporta la scadenza dei dati (assoluta e mobile) e l'elevata disponibilità tramite replica, funzionalità non presenti nelle raccolte .NET standard.

I dati rimangono disponibili. Poiché le strutture sono ospitate nell'ambiente esterno NCache cluster (out-of-proc), sono indipendenti dal ciclo di vita dell'applicazione. I dati sopravvivono a riavvii, arresti anomali e distribuzioni dell'applicazione.

È richiesto un refactoring minimo. NCache implementa interfacce .NET standard come IDictionary<K,V> and IList<T>Puoi usare metodi standard (come Aggiungi, Rimuovi, Contiene) e sostituire semplicemente l'inizializzazione dell'oggetto per utilizzare NCache maniglia.

© Copyright Alachisoft 2002 - . Tutti i diritti riservati. NCache è un marchio registrato di Diyatech Corp.