Estruturas de dados distribuídos em NCache

NCache é um cache distribuído extremamente rápido e escalonável para .NET/.NET Core, Java, Node.js e aplicativos Python. NCache é usado por aplicativos de servidor .NET de alta transação para armazenamento em cache de dados de aplicativos, ASP.NET / ASP.NET Core armazenamento de sessão e mensagens do Pub/Sub.

NCache também se tornou um armazenamento de dados distribuído na memória realmente poderoso, compartilhado entre vários aplicativos .NET e Java. Como resultado, os aplicativos desejam armazenar cada vez mais tipos de dados em NCache para ser compartilhado entre vários aplicativos. Para atender a essa necessidade, NCache fornece estruturas de dados distribuídas em Java e .NET para serem compartilhadas entre vários usuários. Eles são:

Cada uma dessas estruturas de dados é descrita em mais detalhes abaixo.

 

Fila Distribuída

Uma fila distribuída permite criar uma fila para ser compartilhada entre vários aplicativos .NET e Java em execução em um ambiente distribuído. E a Fila garante que a sequência em que você inseriu os dados seja mantida. E todos os aplicativos que recuperam dados da fila podem contar com que essa sequência esteja sempre correta.

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 você pode ver acima, uma Fila Distribuída permite adicionar (Enfileirar) itens em uma sequência para que você possa removê-los posteriormente (Desenfileirar) na mesma sequência (FIFO). Aqui está a interface da Fila Distribuída:

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 você pode ver na interface IDistributedQueue mencionada acima, ela fornece todas as funcionalidades tradicionais do Queue.

 

Conjunto de Hash Distribuído

Um Distributed HashSet se comporta exatamente como a classe .NET HashSet, mas de maneira compartilhada para vários aplicativos e usuários. E, um HashSet fornece todas as operações de Set como:

  • - Sem duplicatas: no conjunto
  • - Definir operações: como União, Intersecção e Diferença

E, sendo um HashSet compartilhado para vários aplicativos ou usuários, isso se torna uma estrutura de dados poderosa para usar. Aqui está um exemplo de como usá-lo.

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 você pode ver, quando você adiciona “Monday” pela segunda vez, ele não é adicionado ao HashSet.

 

Dicionário distribuído

Um Dicionário Distribuído (IDistributedDictionary) se comporta exatamente como a interface .NET IDictionary normal, mas de maneira compartilhada para vários aplicativos e usuários. E um Dicionário Distribuído fornece todas as operações do Dicionário como Adicionar, Atualizar, Remover, Contém e muito mais.

Além dos recursos regulares do Dicionário, o Dicionário Distribuído oferece a capacidade de expirar itens com base em NCache opções de expiração como Expiração Absoluta e Expiração deslizante.

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 você pode ver, o Dicionário Distribuído se comporta como um .NET Distribuído normal (interface IDictionary). Mas, nos bastidores, é distribuído, o que o torna muito escalável. E também é compartilhado entre vários aplicativos.

 

Lista Distribuída

A Lista Distribuída se comporta exatamente como o .NET IList normal, mas com a diferença de que é distribuída e pode ser compartilhada entre vários aplicativos e processos. Lista Distribuída é uma lista não classificada e você pode adicionar itens no final da lista através do Adicionar () método ou em qualquer local através do Inserir () método fornecendo um índice.

Abaixo está um exemplo de como usar uma lista distribuída.

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);

Você também pode remover itens da lista, iterar sobre ela e realizar muitas outras operações.

 

Contador distribuído

Distributed Counter é uma poderosa estrutura de dados em NCache que permite manter um contador exclusivo em um ambiente distribuído compartilhado por vários aplicativos. Isso tem muitos usos e permite desenvolver rapidamente aplicativos em torno dele. Abaixo está um exemplo:

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);

O que fazer a seguir?

NCache Docs
Comparação de edições
Solicite uma demonstração AO VIVO personalizada
Baixar NCache
© Copyright Alachisoft 2002 - . Todos os direitos reservados. NCache é uma marca registrada da Diyatech Corp.