NCache es un caché distribuido extremadamente rápido y escalable para .NET, Java, Node.js, y Python aplicaciones. NCache es utilizado por aplicaciones de servidor .NET de alta actividad transaccional para el almacenamiento en caché de datos de aplicaciones. ASP.NET / ASP.NET Core almacenamiento de sesiones y Mensajería de publicación/suscripción.
NCache ofrece Estructuras de datos distribuidos Que se pueden compartir entre varios usuarios. A diferencia de las estructuras locales que residen en el montón de la aplicación cliente, estas estructuras se alojan en el clúster de caché distribuida, lo que reduce la presión sobre la memoria local y la sobrecarga de la recolección de elementos no utilizados. Estas incluyen:
| Elemento | Recolecciones estándar en proceso | NCache Estructuras distribuidas |
|---|---|---|
| <b></b><b></b> | Limitado al proceso (montón local) | Todo el clúster (recurso de red compartido) |
| Ciclo de Vida | Perdido al reiniciar/reciclar la aplicación | Independiente del ciclo de vida de la aplicación |
| Disponibilidad | Punto único de fallo (el proceso) | Alta disponibilidad (a través de topologías de partición/réplica) |
| Consistencia | Solo es seguro para subprocesos dentro de un único proceso | Coherencia garantizada en múltiples servidores |
Las siguientes secciones proporcionan detalles y ejemplos de código para aplicaciones .NET y Java.
A Cola distribuida implementa el IDistributedQueue<T> Interfaz que permite crear una cola para compartir entre múltiples aplicaciones .NET y Java que se ejecutan en un entorno distribuido. Además, la cola garantiza que se mantenga la secuencia en la que se han introducido los datos. Todas las aplicaciones que recuperan datos de la cola pueden confiar en que esta secuencia siempre será correcta.
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"));
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();
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();
}
A HashSet distribuido Se comporta igual que la clase HashSet de .NET, pero de forma compartida para múltiples aplicaciones y usuarios. Proporciona todas las operaciones de conjunto, como:
Al ser un conjunto hash compartido para múltiples aplicaciones o usuarios, se convierte en una estructura de datos muy útil. A continuación, se muestra 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 = 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");
Como puedes ver, cuando agregas "lunes" por segunda vez, no se agrega al HashSet.
A Diccionario distribuido (IDistributedDictionary) funciona como un sustituto directo de la interfaz IDictionary de .NET, pero de forma compartida para múltiples aplicaciones y usuarios. Proporciona todas las operaciones del diccionario, como Agregar, Actualizar, Eliminar, Contiene, etc.
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 = 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");
Lista distribuida Implementa completamente el System.Collections.Generic.IList<T> Interfaz, lo que le permite actuar como un reemplazo directo de las listas estándar. La diferencia clave es que es distribuida y se puede compartir entre múltiples aplicaciones y procesos. La lista distribuida es una lista sin ordenar, y se pueden agregar elementos al final de la lista mediante el 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 = 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 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 = 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);
IDictionary<K,V> y IList<T>Puedes utilizar métodos estándar (como Agregar, Quitar, Contiene) y simplemente reemplace la inicialización del objeto para usar el NCache encargarse de.© Copyright Alachisoft 2002 - Todos los derechos reservados. NCache es una marca registrada de Diyatech Corp.