Location Affinity [Deprecated]
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
- Install the Alachisoft.NCache.SDK NuGet package.
- Include the following namespaces in your application:
Alachisoft.NCache.ClientAlachisoft.NCache.RuntimeAlachisoft.NCache.Runtime.Exceptions
- The cache must be running.
- Make sure that the data being added is serializable.
- 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.
try
{
// 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);
}
catch (OperationFailedException ex)
{
// High-level NCache exception
if (ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// The customer or order key is already present in the cache
}
else if (ex.ErrorCode == NCacheErrorCodes.NO_SERVER_AVAILABLE)
{
// Connectivity lost with the cache cluster
}
}
catch (ConfigurationException ex)
{
// Occurs if there is an issue with the client configuration
// (e.g., location affinity settings in client.ncconf)
}
catch (Exception ex)
{
// Handles generic errors like ArgumentNullException if FetchCustomerFromDB returns null
}
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 a 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.