Remove Data from Cache
NCache provides the following two overloads with different return types to remove object(s) from the cache by accepting the cache item key(s) as the input parameter.
bool Remove<T>()
void Remove()
Prerequisites
Remove Object From Cache
An object of a custom class can be removed from the cache using any of the Remove()
methods.
Important
If an item does not exist in the cache, null is returned.
Tip
One quick way to verify whether an item has been removed is to use either of the following properties of the Cache class:
Count
returns the number of items present in the cache.
Contains
verifies if a specified key exists in the cache.
The following example removes the item corresponding to the specified key and casts the returned object into a Customer object to check whether the object is of Customer type or not. If not, it is added back to the cache.
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
string customerKey = $"Customer:ALFKI";
// Create an object to store removed item
Customer customerRemoved = null;
// Remove specified item from cache
bool isItemRemoved = cache.Remove(customerKey, out customerRemoved);
if (isItemRemoved)
{
Console.WriteLine($"Customer with ID {customerRemoved.CustomerID} has been removed");
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
try
{
// Pre-condition: Cache is already connected
// Get Product from database against given ProductID
Product product = fetchProductFromDB(1001);
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();
// Remove specified item
cache.remove(key,out removedItem);
// Check if object is returned
if (removedItem != null)
{
// Check if it is of Product type
// Perform operations
}
else
{
// Item does not exist in cache
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like NullPointerException or IllegalArgumentException
}
try {
// Pre-condition: Cache is already connected
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Unique cache key of product to remove
val key = "Product:" + product.getProductId
// Remove specified item
val removedItem = cache.remove(key, classOf[Product])
// Check if object is returned
if (removedItem != null) {
// Perform operations
}
else {
// Item does not exist in cache
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
// This is an async method
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
var key = "Product:" + this.product.getProductID();
// To return item removed
var itemRemoved = new Product();
// Remove specified item
await this.cache.remove(key,itemRemoved);
// Check if object is returned
if (itemRemoved != null)
{
// Check if it is of Product type
if (itemRemoved instanceof Product)
{
// Perform operations
}
else
{
// The object removed was not of Product type
// Add it back to the cache
var ver = await this.cache.add(key, itemRemoved);
}
}
else
{
// Item does not exist in cache
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-condition: Cache is already connected
# Unique cache key of product to remove
key = "Product:1001"
# Remove specified item
item_removed = cache.remove(key, Product)
# Check if object is returned
if item_removed is not None:
# Perform operations
print(item_removed)
else:
# Item does not exist in cache
print("Key not found.")
except Exception as exp:
# Handle errors
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
If you want to save your computational cost, you can use the void Remove()
function that does not return anything and thus performs faster. Here is how you can use it.
string customerKey = $"Customer:ALFKI";
cache.Remove(customerKey);
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();
// Remove specified item
cache.delete(key);
// Unique cache key of product to remove
var key = "Product:" + this.product.getProductID();
// Remove specified item
await this.cache.remove(key);
# Unique cache key of product to remove
key = "Product:1001"
# Remove specified item
cache.delete(key)
// Unique cache key of product to remove
val key = "Product:" + product.getProductId
cache.delete(key)
Remove CacheItem From Cache
NCache allows retrieving an existing CacheItem
from the cache using the dedicated GetCacheItem()
API. This returns a CacheItem
associated with the specified key. Its Value
property encapsulates the data.
The following example retrieves an existing CacheItem
with specified key and checks if the result is of Customer type and type casts it accordingly.
string customerKey = "Customer:ALFKI";
// Retrieve the CacheItem
CacheItem retrievedCacheItem = cache.GetCacheItem(customerKey);
if (retrievedCacheItem != null)
{
Customer customer = retrievedCacheItem.GetValue<Customer>();
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
// Get Product from database against given ProductID
Product product = fetchProductFromDB(1001);
// Get key to fetch from cache
String key = "Product:" + product.getProductID();
// Create a CacheItem
var cacheItem = new ncache.CacheItem(product);
cache.insert(key , cacheItem);
// Get CacheItem from cache
CacheItem retrievedCacheItem = cache.getCacheItem(key);
if (retrievedCacheItem != null)
{
retrievedCacheItem.getValue(Product.class);
// Perform operations according to your business logic
}
else
{
// Null returned; key does not exist
}
def getCacheItem(): Unit = {
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Get key to fetch from cache
val key = "Product:" + product.getProductId
// Create a CacheItem
val cacheItem = CacheItem(product)
cache.insert(key, cacheItem)
// Get CacheItem from cache
val retrievedCacheItem = cache.getCacheItem(key)
if (retrievedCacheItem != null) {
retrievedCacheItem.getValue(classOf[Product])
// Perform operations according to your business logic
}
else {
// Null returned; key does not exist
}
// This is an async method
// Get key to fetch from cache
var key = "Product:" + this.product.getProductID();
// Get CacheItem from cache
var retrievedCacheItem = this.cache.getCacheItem(key);
// Get item against key from cache in given Class type
if (retrievedCacheItem != null)
{
this.cache.getValue(Product);
// Perform your logic
}
else
{
// Null returned; no key exists
}
# Generate key to fetch from cache
key = "Product:1001"
# Get CacheItem from cache
retrieved_cache_item = cache.get_cacheitem(key)
# Get item against key from cache in given Class type
if retrieved_cache_item is not None:
value = retrieved_cache_item.get_value(Product)
# Perform your logic
else:
# Null returned no key exists
print("Key does not exist")
Remove JsonObject From Cache
Note
This feature is only available in NCache Enterprise Edition.
A JsonObject
can be removed from the cache using the Remove
method. The following example removes a JsonObject
from the cache and returns the removed item.
string customerKey = $"Customer:ALFKI";
// JsonObject to be returned
JsonObject customerJObject = null;
bool isItemRemoved = cache.Remove(customerKey, out customerJObject);
if (isItemRemoved)
{
Console.WriteLine($"Customer with ID { customerJObject.GetAttributeValue('CustomerID') } has been removed");
}
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();
JsonObject removedObject = new JsonObject();
// Remove the JsonObject from the cache
cache.remove(key,out removedObject);
if (removedObject != null)
{
// Check if it is of Product type
// Perform operations
}
else
{
// No item removed from the cache
}
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Generate a unique key for this product
val key = "Product:" + product.getProductId
// Create a new JSON object and set attributes
// string values need to be added with JsonValue
val jsonProduct = JsonObject()
jsonProduct.addAttribute("ProductID", JsonValue(product.getProductId))
jsonProduct.addAttribute("ProductName", JsonValue(product.getProductName))
jsonProduct.addAttribute("Category", JsonValue(product.getCategory))
jsonProduct.addAttribute("UnitPrice", JsonValue(product.getPrice))
jsonProduct.addAttribute("UnitsInStock", JsonValue(product.getUnitsAvailable))
cache.insert(key, jsonProduct)
// Remove the JsonObject from the cache
val removedObject = cache.remove(key, classOf[JsonObject])
if (removedObject != null) {
// Check if it is of Product type
// Perform operations
}
else {
// No item removed from the cache
}
Remove Bulk Items From Cache
NCache provides RemoveBulk()
method to remove a bulk of cache items against the specified array of cache keys. It returns a dictionary of the keys and objects removed from the cache.
Important
- If the specified items exist in the cache, a dictionary of the keys and objects removed is returned.
Tip
One quick way to verify whether an item has been removed is to use either of the following properties of the Cache class:
Count
returns the number of items present in the cache.
Contains
verifies if a specified key exists in the cache.
The following example removes a bulk of existing cache items and casts the returned object into Customer objects.
// Create an array of all keys to remove
String[] keysToRemove = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Create dictionary to store removed items
IDictionary<string, Customer> removedItems;
// Remove items from DB
if (DeleteFromDB(keysToRemove))
{
// Remove bulk items from cache
cache.RemoveBulk(keysToRemove, out removedItems);
if (removedItems.Count != keysToRemove.Length)
Console.WriteLine($"Failed to remove {keysToRemove.Length - removedItems.Count} items from cache.");
}
// Get products to remove
Product[] products = fetchProducts();
// Specify keys to remove from cache
ArrayList<String> keys = new ArrayList<>(products.length);
for (Product product : products)
{
String key = "Product:" + product.getProductID();
keys.add(key);
cache.insert(key , product);
}
// Remove items
java.util.Map<String, Product> removedItems = cache.removeBulk(keys, Product.class);
// If items have been returned
if (removedItems.size() > 0)
{
for (java.util.Map.Entry<String, Product> entry : removedItems.entrySet())
{
if (entry.getValue() != null)
{
Product product = entry.getValue();
// Save object for future use as Product object
}
else
{
// Object not of Product class
}
}
}
else
{
// No objects removed
}
// Get products to remove
val products = fetchProducts
// Specify keys to remove from cache
var keys: List[String] = List()
for (product <- products) {
val key = "Product:" + product.getProductId
keys = key :: keys
cache.insert(key, product)
}
// Remove items
val removedItems = cache.removeBulk(keys, classOf[Nothing])
// Check if items returned
if (removedItems.size == keys.size) {
for (entry <- removedItems) {
// Perform operations according to business logic
}
}
else {
// Not all of the keys are present in cache
}
// This is an async method
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();
// Get keys to fetch from cache
var keys = [products.length];
var index = 0;
products.forEach(product => {
keys[index] ="Product:" + this.product.getProductID();
index++;
});
// Get bulk from cache
var removedItems = await this.cache.removeBulk(keys);
// Check if any keys have failed to be retrieved
if(removedItems.size() > 0)
{
removedItems.forEach(entry => {
if(entry.getValue() instanceof Product)
{
var prod = entry.getValue();
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
});
}
else
{
// No objects removed
}
# Get Products from database
products = fetch_products_from_db()
# Get keys to remove from cache
keys = []
index = 0
for product in products:
keys[index] = "Product:" + product.get_product_id()
index = index + 1
# Remove bulk from cache
removed_items = cache.remove_bulk(keys, Product)
# Check if any keys have failed to be removed
if len(removed_items) is len(keys):
# Perform operations according to business logic
print("All the items were removed successfully")
else:
# Not all the keys are present in cache
print("Some of the keys were not removed")
Remove Objects From Cache With Asynchronous API
Note
This feature is only available in NCache Enterprise Edition.
RemoveAsync()
returns object of the Task class that can be further used according to the business needs of the client application. NCache provides three different status flags to notify the success or failure of the operation.
Important
- Unlike
Remove()
and RemoveBulk()
, RemoveAsync()
does not generally return the removed objects to the application as it is an asynchronous operation and has to be fetched.
string customerKey = $"Customer:ALFKI";
// Remove specified item from cache
Task<Customer> task = cache.RemoveAsync<Customer>(customerKey);
//This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get Customer object from task result
Customer customer = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been removed.");
}
// Get Product from database against given ProductID
Product product = fetchProductFromDB(1001);
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();
// Create a CacheItem
var cacheItem = new ncache.CacheItem(product);
cache.insert(key,cacheItem);
// Asynchronously remove items from cache
FutureTask<Product> task = cache.<Product>removeAsync(key,Product.class);
//This task object can be used as per your business needs
if (task.isDone())
{
// Task completed
}
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Unique cache key of product to remove
val key = "Product:" + product.getProductId
// Create a CacheItem
val cacheItem = CacheItem(product)
cache.insert(key, cacheItem)
// Asynchronously remove items from cache
val task = cache.removeAsync(key, classOf[Product])
//This task object can be used as per your business needs
if (task.isCompleted) {
// Task completed
}
# Generate a unique cache key for this product
key = f"Product:1001"
# Remove Product object from cache asynchronously
async def remove_async():
task = cache.remove_async(key, Product)
value = await task
asyncio.run(remove_async())
# This task object can be used as per your business needs
Additional Resources
NCache provides the sample application for Basic Operations on GitHub.
See Also
Data Structures in Cache
JSON Data in cache
How to Connect to Cache
Add Data to Cache
Start Cache