Remove Data from Cache
For large amount of data in cache, there can be some data which turns stale over time or is not needed for further operations by the application. For this, NCache allows removing items from the cache, which frees up space in the cache and ensures data consistency and freshness.
NCache provides two overloads of the Remove function to facilitate removal of objects from the cache. These two overloads take the cache item key(s) as their parameter. While both overloads remove the specified items from the cache, they have difference in their return types which makes their uses unique and more flexible.
bool Remove |
void Remove() |
---|---|
Returns the removed object to the application in Template type. | Returns nothing. |
bool Remove()
This is a fail safe option, as it allows checking whether the data removed should be really removed or not. In case the object removed is not the one you wanted to remove, the returned object can be added back to the cache.
For example, you want to remove a Product type object from the cache but the key provided is not explanatory to describe whether the object is Product type or not. Here, you can check whether the data removed is of Product data type. If it is not, it means the wrong object has been removed, and you can add it back to the cache.
Another use of this overload can be an e-commerce site which needs to remove the products which have less than 3 units available at the end of each business day. Hence, using this overload will remove the items from the cache, but return the objects back to the application so that a list of products running low on units can be maintained.
void Remove()
This approach is a faster operation compared to bool Remove<T>
, as it does not have the added operational cost of fetching the objects and returning them to the application. It can be used when you are sure of the data being removed.
For example, an e-commerce site removes those products which have been marked as "discontinued" in the data source but are still residing in the cache. In such a scenario, using this overload will be more efficient as the application does not require keeping track of the products which are no longer available.
Remove Operation Behavior
Data can be removed from NCache either as a single item, bulk of items or asynchronously.
bool Remove
will return the removed object to the application. If the keys specified do not exist, null will be returned and no exception will be thrown. void Remove will return nothing to the application. If the keys specified do not exist, no exception will be thrown.
In advanced cases, if data source is configured, data removal will occur in cache as well as data source. For more details, you can refer to the chapter Data Source Providers.
Pre-requisites
- Include the following namespace in your application:
Alachisoft.NCache.Client
.Alachisoft.NCache.Runtime.Exceptions
- The application must be connected to cache before performing the operation.
- Cache must be running.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Single Object
A single item can be removed from the cache, which is also returned to the application through the Remove() method. For Java, use the Remove() method to remove the object from the cache.
Important
If the item does not exist in cache, null is returned.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following example removes the item corresponding to the specified key and casts the returned object into a Product
object to check whether the object is of Product type. 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}";
// To return item removed
Product itemRemoved = new Product();
// Remove specified item
cache.Remove(key, out itemRemoved);
// Check if object is returned
if (itemRemoved != null)
{
// Check if it is of Product type
if (itemRemoved is Product)
{
// Perform operations
}
else
{
// The object removed was not of Product type
// Add it back to the cache
CacheItemVersion ver = cache.Add(key, itemRemoved);
}
}
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 ArgumentNullException or ArgumentException
}
If you want to save your computational cost, you can use the void Remove function which will not return anything and is much faster than the previous one.
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
// Remove specified item
cache.Remove(key);
}
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
}
JsonObject
Note
This feature is only available in NCache Enterprise Edition.
A JsonObject
can be removed from the cache using the Remove method. Using this method, you can remove an item and the removed item is returned. Another overload of Remove method removes a JsonObject
from the cache and returns nothing.
The following example removes a JsonObject
from the cache and returns the removed item.
try
{
// Specify the unique key for JsonObject
string key = "Product:1001";
// JsonObject to be returned
var jsonObj = new JsonObject();
// Remove the JsonObject from the cache
cache.Remove(key, out jsonObj);
if (jsonObj != null)
{
// Check if it is of Product type
if (jsonObj is JsonObject)
{
// Perform operations
}
else
{
// The object removed was not JsonObject
}
}
else
{
// No item removed from the 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 ArgumentNullException or ArgumentException
}
Data Structures
Note
This feature is only available in NCache Enterprise Edition.
An existing data type can be removed from the cache using Remove. The following code removes an existing List from cache and returns it to the client. For more detail on supported data structures, please refer to the section Data Structures in Cache.
try
{
// Pre-condition: Cache is already connected
// Specify key of list to be removed
string keyToRemove = "ProductList";
// Create a list to store returned object
IDistributedList<Product> returnedList = cache.DataTypeManager
.CreateList<Product>("ReturnedList");
// Remove list and return value
cache.Remove(keyToRemove, out returnedList);
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.ErrorCode == NCacheErrorCodes.NOT_A_LIST)
{
// The type of the corresponding item is not a list
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Bulk Items
NCache provides RemoveBulk() method to remove a bulk of cache items against the specified array of cache keys. This returns a dictionary of the keys and objects removed from the cache. For Java, use the removeBulk() method to remove a bulk of items from the cache.
Important
- If the specified items exist in cache, a dictionary of the keys and objects removed is returned.
- If the specified items do not exist in cache, nothing is returned for those items.
Although a bulk operation is executed as a single operation, the failure of operations is treated individually. For example, if a bulk of 100 items is removed from the cache and 20 of those items do not exist in the cache, the remaining 80 items will be removed from the cache and return to the application.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
The following example removes a bulk of existing cache items, and casts the returned object into Product
objects.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
// Get products to remove
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;
// Remove items
cache.RemoveBulk(keys, out removedItems);
// If items have been returned
if (removedItems.Count > 0)
{
foreach (KeyValuePair<string, Product> entry in removedItems)
{
if (entry.Value is Product)
{
Product product = entry.Value;
// Save object for future use as Product object
}
else
{
// Object not of Product class
}
}
}
else
{
// No objects 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
}
Asynchronous API
Note
This feature is only available in NCache Enterprise Edition.
Asynchronous operations are performed in the background, so the client does not have to wait for the response from the server to execute further operations. The list of actions to be performed on the cache is maintained in a queue at the client side and a dedicated background thread keeps on sending them to the server side. Hence, all the operations are being executed in a pure asynchronous manner, increasing the efficiency of the client application.
RemoveAsync returns object of the Task class which can further be 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. For Java, use the removeAsync method to remove the items from the cache asynchronously.
IsCanceled: Notifies if the RemoveAsync function is canceled.
IsCompleted: Notifies if the RemoveAsync function is completed.
IsFaulted: Notifies if the RemoveAsync function is faulted.
Important
- Unlike Remove and RemoveBulk, RemoveAsync does not return the removed objects to the application as it is an asynchronous operation.
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
// Asynchronously remove items from cache
Task<Product> task = cache.RemoveAsync<Product>(key);
//This task object can be used as per your business needs
if (task.IsFaulted)
{
// Task completed due to an unhandled exception
}
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Additional Resources
NCache provides sample application for Basic Operations at:
- GitHub
- Shipped with NCache: %NCHOME%\samples\dotnet\BasicOperations
See Also
How to Connect to Cache
Add Data to Cache
Update Existing Data in Cache
Retrieve Existing Cache Data
Start Cache