Uso de caché de escritura subyacente
Esta sección explica el uso del modo de escritura subyacente después de implementar y configurar el proveedor de escritura simultánea. Write-Behind actualiza la fuente de datos de forma asincrónica después de actualizar el almacén de caché.
Importante:
Para Java, antes de implementar sus archivos JAR, debe asegurarse de que:
- JDK 17 está instalado.
- La variable de entorno para Java está configurada.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache funciones del lado del servidor, consulte la página dada en Requisitos previos de la API del lado del servidor.
- Para obtener detalles de la API, consulte: Artículo de caché, Recibe, recuadro, IWriteThruProvider, Eliminar, Insertar a granel, Quitar a granel, Insertar asíncrono, EliminarAsync.
Agregar/actualizar con escritura posterior
Puede agregar/actualizar elementos de caché con o sin devolución de llamada en el caché junto con Write-Behind habilitado. Agregar con devolución de llamada le notifica sobre el tipo de evento ocurrido que registra.
Agregar sin método de devolución de llamada
El siguiente ejemplo agrega un elemento en el caché con Write-Behind habilitado, usando el Insert()
método. Con este método, si un elemento ya está presente en la memoria caché, el nuevo valor sobrescribe el valor anterior.
// Pre-Condition: Cache is already connected
// Specify the key of the cacheItem
Product product = FetchProductByProductID(1001);
string key = $"product:ProductID";
var cacheItem = new CacheItem(product);
// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
// Add item in the cache with write-behind
cache.Insert(key, cacheItem, writeThruOptions);
Note
Para garantizar que la operación sea a prueba de fallas, se recomienda manejar cualquier posible excepción dentro de su aplicación, como se explica en Manejo de fallas.
Agregar con método de devolución de llamada
El siguiente ejemplo agrega un elemento en el caché con devolución de llamada registrada y tipo de evento de ItemAdded
con Write-Behind activado.
// Specify the key of the cacheItem
Product product = FetchProductByProductID(1001);
string key = $"product:ProductID";
var cacheItem = new CacheItem(product);
// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
// Add item in the cache with write-behind
cache.Insert(key, cacheItem, writeThruOptions);
Eliminar datos existentes con escritura posterior
El siguiente ejemplo elimina el elemento de la memoria caché con Write-Behind habilitado, utilizando el Remove
método, correspondiente a la clave proporcionada, así como de la fuente de datos y registra los eventos para la operación.
// Specify the key of the item
string key = "Product:1001";
// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Remove the item corresponding to the key with write-through enabled
cache.Remove(key, null, null, writeThruOptions);
Operaciones masivas
Agregar/actualizar elementos masivos con escritura posterior
El siguiente ejemplo agrega elementos masivos en el caché con Write-Behind habilitado, usando el InsertBulk()
método. Si los elementos ya están presentes en la memoria caché, los valores nuevos sobrescriben los valores existentes.
// Fetch all products from database
Product[] products = FetchProductsFromDB();
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemUpdated);
IDictionary<string, CacheItem> dictionary = new Dictionary<string, CacheItem>();
foreach(var product in products)
{
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);
dictionary.Add(key, cacheItem);
}
IDictionary<string, Exception> keysFailedToUpdate = cache.InsertBulk(dictionary, writeThruOptions);
Eliminar elementos existentes con escritura posterior
El siguiente ejemplo elimina una gran cantidad de elementos de la memoria caché con Write-Behind habilitado, utilizando el RemoveBulk()
método.
// Get Keys
Product[] products = FetchProductsFromDB();
// Specify keys to remove from cache
string[] keys = new string[products.Length];
int index = 0;
foreach (var product in products)
{
keys[index] = $"Product:{product.ProductID}";
index++;
}
// Create dictionary to store removed items
IDictionary<string, Product> removedItems = new Dictionary<string,Product>();
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Remove items with write-behind enabled
cache.RemoveBulk(keys, out removedItems, writeThruOptions);
Note
Usa el método OnDataSourceItemsRemoved()
para realizar operaciones después de la eliminación de datos de la memoria caché.
Operaciones asíncronas
Agregar/Actualizar elemento con escritura posterior
El siguiente ejemplo agrega un elemento de forma asincrónica en caché con Write-Behind habilitado, usando el InsertAsync()
método.
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);
// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
// Add Product object to cache
Task task = cache.InsertAsync(key, cacheItem, writeThruOptions);
Eliminar el elemento con escritura posterior
El siguiente ejemplo elimina los elementos existentes de forma asíncrona de la memoria caché con Write-Behind habilitado, utilizando el RemoveAsync()
método.
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Asynchronously remove items from cache
Task<Product> task = cache.RemoveAsync<Product>(key, writeThruOptions);
Usar estructuras de datos con escritura posterior
El siguiente ejemplo utiliza diferentes estructuras de datos con Write-Behind habilitado, en el elemento especificado.
// Specify the key of the item
string key = "Product:1001";
var dataTypeAttributes = new DataTypeAttributes();
var writeThruOptions = new WriteThruOptions(WriteMode.WriteBehind, WriteThruProviderName);
switch(mainMenu)
{
case mainMenu.GetDistributedCounter:
// Modify or add count of the corresponding item with write thru enabled
var distributedCounter = cache.DataTypeManager.CreateCounter("counter", dataTypeAttributes, 0, writeThruOptions);
// perform operations on counter
break;
case mainMenu.GetDistributedDictionary:
// Modify or add dictionary of the corresponding item with write thru enabled
var distributedDictionary = cache.DataTypeManager.CreateDictionary<string, int>(key, dataTypeAttributes, writeThruOptions);
// perform operations on dictionary
break;
case mainMenu.GetDistributedList:
// Modify or add the list of the corresponding item with write thru enabled
var distributedList = cache.DataTypeManager.CreateList<int>("list", dataTypeAttributes, writeThruOptions);
// perform operations on list
break;
case mainMenu.GetDistributedQueue:
// Modify or add the queue of the corresponding item with read thru enabled
var distributedQueue = cache.DataTypeManager.CreateQueue<int>("queue", dataTypeAttributes, writeThruOptions);
// perform operations on queue
break;
case mainMenu.GetDistributedHashSet:
// Modify or add the HashSet of the corresponding item with read thru enabled
var distributedHashSet = cache.DataTypeManager.CreateHashSet<int>("hashset", dataTypeAttributes, writeThruOptions);
// perform operations on hashset
break;
}
Recursos adicionales
NCache proporciona una aplicación de muestra para Write-Behind en GitHub.
Vea también
.NETO: Alachisoft.NCache.Tiempo de ejecución espacio de nombres
Java: com.alachisoft.ncache.runtime.datasourceprovider espacio de nombres