Location Affinity
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 items 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.
// Precondition: 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);
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.
See Also
.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client class.
Node.js: Cache class.