Location Affinity in NCache
Note
This feature is available in NCache Enterprise Edition only.
NCache provides a mechanism to store data in the cache that creates an affinity between items of different classes. You can store items of different types on the same node to save the matching cost while fetching items with similar keys. This mechanism maps similar entries at the backend, thus further speeding up fetch operations.
Prerequisites
- To learn about the standard prerequisites required to work with all NCache client side features please refer to the given page on Client Side API Prerequisites.
- For API details, refer to: Add, CacheItem, CacheItemVersion, ICache.
Adding item with Location Affinity
Location affinity can be enabled manually while entering data into the cache. The item key must be the same inside braces {}
as in the other item. For example, to create location affinity between Customer and Order objects, you can specify the key "Customer:1001" for a Customer object in the cache and then create an affinity of the associated order by specifying "Customer:1001" within {}
. So the Order object key can be specified as "Order_{Customer:1001}". This will ensure that the customers and orders exist within the same node.
try
{
// Pre-condition: Cache is already connected
Customer customer = FetchCustomerFromDB(1001);
string customerKey = "Customer:1001";
var customerCacheItem = new CacheItem(customer);
// Add CacheItem to cache
cache.Add(customerKey, customerCacheItem);
Order order = FetchOrderFromDB(1001);
// Unique orderKey for this order using location affinity syntax
// This will create an affinity for this orderKey with the respective customerKey
string orderKey = "Order_{"+ customerKey +"}";
var orderCacheItem = new CacheItem(order);
// Add order with location affinity to the cache
cache.Add(orderKey, orderCacheItem);
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// An item with the same key already exists
}
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
}
Note
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 using location affinity on GitHub.