Aggiorna/Inserisci dati esistenti nella cache
NCache fornisce il Insert
metodo e i suoi sovraccarichi per facilitare l'aggiornamento degli oggetti nella cache. Mentre sovrascrive i dati per gli elementi esistenti, aggiunge anche l'elemento alla cache se la chiave non esiste nella cache.
Prerequisiti
- Per conoscere i prerequisiti standard richiesti per lavorare con all NCache Per le funzionalità lato client fare riferimento alla pagina specificata Prerequisiti dell'API lato client.
- Per i dettagli dell'API fare riferimento a: ICache, CacheItemVersion, CacheItem, inserire, Ottieni, Inserisci in blocco, InserisciAsync.
Aggiorna oggetto nella cache
Note:
Questa funzionalità è disponibile anche in NCache Professional.
Puoi aggiornare un oggetto personalizzato nella cache usando vari overload di Insert
metodo. Questo restituisce a CacheItemVersion
.
Consigli
- Se la chiave esiste già, sovrascriverà l'elemento della cache esistente con la stessa chiave.
- Se la chiave non esiste, l'operazione aggiunge invece l'elemento alla cache.
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.
L'esempio seguente ottiene i valori di un oggetto esistente e lo inserisce nella cache con la stessa chiave. Se la chiave non esiste, la aggiunge alla cache.
// Precondition: Cache is already connected
string customerKey = "ALFKI";
// Get updated product from database against given product ID
Customer customer = FetchProductFromDB("ALFKI");
// Insert Product object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);
// Item updated in cache successfully
Aggiorna oggetto con scadenza
Note:
Questa funzionalità è disponibile anche in NCache Professional.
CacheItem
è una classe personalizzata fornita da NCache che può essere utilizzato per aggiungere dati alla cache e consente inoltre di impostare specifiche aggiuntive associate a un oggetto come proprietà di questa classe. Il CacheItem viene aggiornato nella cache rispetto a una chiave univoca.
Consigli
- Se la chiave esiste già, sovrascriverà l'elemento della cache esistente con la stessa chiave.
- Se la chiave non esiste, l'operazione aggiunge invece l'elemento alla cache.
L'esempio seguente ottiene i valori aggiornati di un CacheItem esistente e lo inserisce nella stessa chiave nella cache. Se la chiave non esiste, la aggiunge alla cache.
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB("ALFKI");
// Update Customer's Phone
customer.Phone = "0921-12 34 65";
// Cretae CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
// Update cutsomer in DB and Cache
if (UpdateDB(customer))
{
cache.Insert(customerKey, cacheItem);
}
Aggiorna gli elementi in blocco nella cache
Note:
Questa funzionalità è disponibile anche in NCache Professional.
InsertBulk
aggiorna una matrice di CacheItem
alla cache contro la chiave corrispondente. Il metodo restituisce un dizionario di tutte le chiavi che non sono state aggiornate, insieme al motivo dell'errore.
Consigli
Se l'aggiornamento di una chiave non riesce, i motivi dell'errore verranno restituiti come file IDictionary
.
L'esempio di codice seguente recupera una matrice di prodotti (di tipo) dal database. I prodotti vengono quindi inseriti nella cache come dizionario di chiavi e CacheItem
utilizzando InsertBulk
.
// Create an array of all Customer Keys
String[] keys = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Get items from cache
IDictionary<string, Customer> itemsFetched = cache.GetBulk<Customer>(keys);
//Create a dictionary to store updated items
IDictionary<string, CacheItem> itemsUpdated = new Dictionary<string, CacheItem>();
// Update postal codes of dictionary items
foreach (KeyValuePair<string, Customer> item in itemsFetched)
{
//Update Postal Code
item.Value.PostalCode = "05023";
// Create CacheItem of updated Customer object
CacheItem updatedCacheItem = new CacheItem(item.Value);
// Add uCacheItem to dictionary
itemsUpdated.Add(item.Key,updatedCacheItem);
}
if (UpdateDB(itemsUpdated))
{
// Insert updated bulk items to Cache
IDictionary<string, Exception> keysFailedToInsert = cache.InsertBulk(itemsUpdated);
if (keysFailedToInsert.Count > 0)
{
foreach (KeyValuePair<string, Exception> keyFailedToInsert in keysFailedToInsert)
Console.WriteLine($"Could not update Item {keyFailedToInsert.Key} in cache due to error : {keyFailedToInsert.Value}");
}
}
Aggiorna oggetti con l'API asincrona
InsertAsync
restituisce l'oggetto di Classe di attività che può essere ulteriormente utilizzato in base alle esigenze aziendali dell'applicazione client.
string customerKey = $"Customer:ALFKI";
// Get customer from database if not found in cache
if (customer == null)
customer = FetchCustomerFromDB("ALFKI");
// Update customer's Phone
customer.Phone = "12345-6789";
// Update cutsomer in DB and Cache
if (UpdateDB(customer))
{
// Adding item asynchronously.
Task<CacheItemVersion> task = cache.InsertAsync(customerKey, customer);
// This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get CacheItemVersion object from task result
CacheItemVersion version = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been updated with verion {version.Version}.");
}
}
Risorse addizionali
NCache fornisce un'applicazione di esempio per Operazioni di base su GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Cliente spazio dei nomi.
Giava: com.alachisoft.ncache.cliente spazio dei nomi.
Node.js: Cache classe.
Pitone: ncache.cliente classe.