Estructuras de datos distribuidos en NCache

NCache es un caché distribuido extremadamente rápido y escalable para .NET/.NET Core, Aplicaciones Java, Node.js y Python. NCache es utilizado por aplicaciones de servidor .NET de alta transacción para el almacenamiento en caché de datos de aplicaciones, ASP.NET / ASP.NET Core almacenamiento de sesión y mensajería Pub/Sub.

NCache También se ha convertido en un almacén de datos distribuido en memoria realmente poderoso que se comparte entre múltiples aplicaciones .NET y Java. Como resultado, las aplicaciones quieren almacenar cada vez más tipos de datos en NCache para ser compartido entre múltiples aplicaciones. Para hacer frente a esta necesidad, NCache proporciona estructuras de datos distribuidas en Java y .NET para compartir entre varios usuarios. Ellos son:

Cada una de estas estructuras de datos se describe con más detalle a continuación.

 

Cola distribuida

Una cola distribuida le permite crear una cola para compartir entre múltiples aplicaciones .NET y Java que se ejecutan en un entorno distribuido. Y la cola garantiza que se mantenga la secuencia en la que ingresó los datos. Y todas las aplicaciones que recuperan datos de la cola pueden confiar en que esta secuencia sea siempre correcta.

string cacheName = "demoCache";
string QueueName = "DistributedQueue:Customers";
  
// Initialize an instance of the cache to begin performing operations:
ICache cache = NCache.Client.CacheManager.GetCache(cacheName);
  
// Creating a named distributed queue
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);

// Creating a named distributed queue
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"));

Como puede ver arriba, una cola distribuida le permite agregar (poner en cola) elementos en una secuencia para que luego pueda eliminarlos (quitarlos) en la misma secuencia (FIFO). Aquí está la interfaz de cola distribuida:

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();
	void Enqueue(T item);
	T Peek();
	T[] ToArray();
}
public interface DistributedQueue<T> extends Queue<T>, DistributedDataStructure, Notifiable 
{
	void clear();
	void copyTo(T[] array, int arrayIndex);

	T peek();

	public interface Queue<E> extends Collection<E> {
		boolean add(E e);
		E remove();
	}

	public interface Collection<E> extends Iterable<E> {
		boolean contains(Object o);
	}
}

Como puede ver en la interfaz IDistributedQueue mencionada anteriormente, le proporciona toda la funcionalidad de cola tradicional.

 

HashSet distribuido

Un HashSet distribuido se comporta como la clase HashSet de .NET pero de manera compartida para múltiples aplicaciones y usuarios. Y, un HashSet proporciona todas las operaciones Set como:

  • - Sin duplicados: en el conjunto
  • - Establecer operaciones: como unión, intersección y diferencia

Y, al ser un HashSet compartido para múltiples aplicaciones o usuarios, se convierte en una poderosa estructura de datos para usar. Aquí hay un ejemplo de cómo usarlo.

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

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

// Creating 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 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");

Como puede ver, cuando agrega "Lunes" por segunda vez, no se agrega al HashSet.

 

Diccionario distribuido

Un diccionario distribuido (IDistributedDictionary) se comporta como la interfaz IDictionary de .NET normal, pero de forma compartida para múltiples aplicaciones y usuarios. Y, un diccionario distribuido proporciona todas las operaciones del diccionario como Agregar, Actualizar, Eliminar, Contiene y más.

Además de las funciones habituales del Diccionario, el Diccionario distribuido ofrece la posibilidad de hacer caducar elementos en función de NCache opciones de vencimiento como Caducidad absoluta y Caducidad móvil.

ICache cache = NCache.Client.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 distributed Dictionary with 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");

Como puede ver, el Diccionario distribuido se comporta como un .NET distribuido normal (interfaz IDictionary). Pero, entre bastidores, está distribuido, lo que lo hace muy escalable. Y también se comparte entre múltiples aplicaciones.

 

Lista distribuida

La lista distribuida se comporta igual que la IList de .NET normal, pero con la diferencia de que está distribuida y puede compartirse entre múltiples aplicaciones y procesos. La lista distribuida es una lista sin ordenar y puede agregar elementos al final de la lista a través del Añadir () método o en cualquier lugar a través del Insertar () método proporcionando un índice.

A continuación se muestra un ejemplo de cómo utilizar una lista distribuida.

ICache cache = NCache.Client.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);

También puede eliminar elementos de la lista, iterarlos y realizar muchas otras operaciones.

 

contador distribuido

Distributed Counter es una poderosa estructura de datos en NCache que le permite mantener un contador único en un entorno distribuido compartido por múltiples aplicaciones. Esto tiene muchos usos y le permite desarrollar rápidamente aplicaciones a su alrededor. A continuación se muestra un ejemplo:

ICache cache = NCache.Client.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);

¿Qué hacer a continuación?

NCache Docs
Comparación de ediciones
Solicite una demostración EN VIVO personalizada
Descargar NCache
© Copyright Alachisoft 2002 - Todos los derechos reservados. NCache es una marca registrada de Diyatech Corp.