Key Data Dependency Types and Usage
There are situations when you want to keep a relationship among related cache data. For example, if an order depends on a product that is no longer available, the cache must remove all its dependents, as well. Here you can use the Key Dependency to maintain this relationship. Essentially, a Key Dependency creates a dependency relationship between cached items.
Note
The dependent item is removed in case of two types of modifications in the master key:
- Update
- Remove
In NCache, dependent cache items and those on whom others depend are aware of this relationship. When the cache removes such an item on which other cache items depend, it will also remove all its dependents. However, vice versa is not possible. For example, Products will not be removed, if any of the Orders are updated or removed.
Key(s) can have two types of dependencies:
Multilevel Dependency
A cache item can depend on any number of other items in the cache; resulting in the formation of a chain. The relationship, in this case, will be a 1:1 relationship. For instance, if there are three data sets in a cache - i.e., Products, Orders, and OrderDetails - an order placed on a particular Product, the key of the OrderDetails depends on the key of the Orders. Similarly, the key of the Orders depends on the key of the Products. This means that if the Products are deleted, the Orders and the OrderDetails are also deleted. The following diagram depicts this scenario visually.
Multiple Dependency
A single item can depend on more than one item in the cache. Similarly, that item may depend on multiple items. This may result in a 1:n relationship between the items. For example, in a cache, if an Order is placed by a Customer which contains a Product, the Order depends on the Customer and Product. Similarly, the OrderDetails depend on the Orders. The following diagram depicts the whole scenario visually.
If the Customer is deleted, Orders and OrderDetails get deleted. Similarly, if the Product is deleted, Orders and OrderDetails get deleted.
Note
You can only specify existing keys in a cache for Key Dependency. A non-existent key specified for Key Dependency will result in an OperationFailedException
. Whereas an object can be considered dependent on another key at the time of addition.
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: ICache, CacheItem, CacheItemAttributes, Dependency, UpdateAttributes, Insert.
Add CacheItem to Cache with Key Data Dependency
The CacheItem
is a custom class provided by NCache that can be used to add data to the cache and lets you set additional metadata associated with an object of this class. This metadata defines the item properties like dependencies, expirations, and more.
The Add method adds a new item in the cache, whereas the Insert method adds a new item with dependency. If this CacheItem
already exists in the cache, it overwrites its properties.
Important
Note that this API also specifies CacheItem
priority for Eviction and Expiration, where the value for that parameter is passed as Default
.
The following example adds a CacheItem
order to the cache using the Insert
method, which is dependent on the customer in the cache, which means as soon as the customer is updated or deleted, the order of the customer is already deleted from the cache.
// Precondition: Cache is already connected
// Get customer from database
Customer customer = FetchCustomerFromDB();
// Add customer in cache
cache.Add(customer.CustomerID, customer);
// Get order from customer
Order order = new Order
{
OrderID = 10248,
OrderDate = DateTime.Now,
ShipAddress = "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
bool isOrderSaved = SaveOrderToDB(order);
// Generate order Id
string orderKey = $"Order:{order.OrderID}";
if (isOrderSaved)
{
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(customer.CustomerID);
// Create CacheItem to with your desired object
CacheItem cacheItem = new CacheItem(order);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Add order in cache with dependency on the customer added before
cache.Add(orderKey, cacheItem);
}
OrderDetail orderDetail = new OrderDetail
{
OrderID = order.OrderID,
UnitPrice = 200,
Discount = 25.5F,
Quantity = 10,
};
// Save order's detail to database
bool isOrderDetailSaved = SaveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
string orderDetailId = $"OrderDetail: {orderDetail.OrderID}";
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem to with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Add order in cache with dependency on the customer added before
cache.Add(orderDetailId, cacheItem);
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Key Dependency on Multiple Keys
You can also add Key Dependency to an item, which is dependent on multiple keys. This way a single item can be dependent on multiple items using the Add or Insert method.
The Add
method adds a new item in the cache whereas the Insert
method adds a new item with dependency, and if the item already exists in the cache it overwrites its properties. The following example demonstrates this.
// Get customer from database
Customer customer = FetchCustomerFromDB();
// Get product from database
Product product = FetchProductFromDB();
// Add customer in cache
cache.Add(customer.CustomerID, customer);
// Add product to cache.
string productId = $"Product: {product.ProductID}";
cache.Add(productId, product);
// Get order from customer
Order order = new Order
{
OrderID = 10248,
OrderDate = DateTime.Now,
ShipAddress = "Carrera 22 con Ave. Carlos Soublette #8-35"
};
// Save order to database
bool isOrderSaved = SaveOrderToDB(order);
// Generate order Id
string orderKey = $"Order: {order.OrderID}";
if (isOrderSaved)
{
string[] dependencyKeys = { productId, customer.CustomerID };
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(dependencyKeys);
// Create CacheItem to with your desired object
CacheItem cacheItem = new CacheItem(order);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Add order in cache with dependency on the customer added before
cache.Add(orderKey, cacheItem);
}
OrderDetail orderDetail = new OrderDetail
{
OrderID = order.OrderID,
UnitPrice = 200,
Discount = 25.5F,
Quantity = 10,
};
// Save order's detail to database
bool isOrderDetailSaved = SaveOrderDetailToDB(orderDetail);
if (isOrderDetailSaved)
{
// Generate order detail Id
string orderDetailId = $"OrderDetail: {orderDetail.OrderID}";
// Generate an instance of Key Dependency
CacheDependency dependency = new KeyDependency(orderKey);
// Create CacheItem to with your desired object
CacheItem cacheItem = new CacheItem(orderDetail);
// Add Key Dependency to order
cacheItem.Dependency = dependency;
// Add order in cache with dependency on the customer added before
cache.Add(orderDetailId, cacheItem);
}
Add Key Dependency to Existing Cache Item
NCache lets you add a Key Dependency to an item already present in the cache, without re-inserting it into the cache. This process occurs through the CacheItemAttribute
class, which has the property of Dependency
to be set against CacheItem
. The attribute is then set against the existing key of the item, using the UpdateAttributes
method of the Cache
class.
The following example shows that an order and a customer are already present in the cache without dependency, and dependency is added using UpdateAttributes
such that if the customer is updated or removed in the cache, the order is automatically removed.
string orderId = "Order: 10248";
string ProductId = "Product: 8899";
// Create a Key Dependency where order is dependent on product
CacheDependency dependency = new KeyDependency(ProductId);
// Create a cache item attribute
CacheItemAttributes itemAttribute = new CacheItemAttributes();
// Set dependency to cache item attribute
itemAttribute.Dependency = dependency;
// Update attribute in cache
cache.UpdateAttributes(orderId, itemAttribute);
Additional Resources
NCache provides a sample application for Key Dependency on GitHub.
See also
.NET: Alachisoft.NCache.Runtime.Dependencies namespace.
Java: com.alachisoft.ncache.runtime.dependencies namespace.
Python: ncache.runtime.dependencies class.
Node.js: Key Dependency class.