Add Data to Cache
After successfully connecting to the cache and gaining a valid cache handle, you can add data to the cache. NCache provides the Add
method and its overloads to facilitate adding objects to cache for the first time.
Prerequisites to Add Data to Cache
- 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, Add, Insert, CacheItem, CacheItemVersion, Count, Contains, AddBulk, AddAsync.
Add Object to Cache
Note
This feature is also available in NCache Professional.
You can add an object of a custom class to the cache using various overloads of the Add
method.
Warning
If the key already exists, "The specified key already exists" exception will be thrown.
The following example adds an object of the Product class and its associated key into the cache.
Tip
One quick way to verify whether an item has been added is to use either of the following properties of the Cache class:
Count
returns the number of items present in the cache.Contains
verifies if a specified key exists in the cache.
// Precondition: Cache is already connected
// Get customer from database
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// Get customer from database if not found in cache
if (customer == null)
{
// Get customer from database
customer = FetchCustomerFromDB("ALFKI");
cache.Add(customerKey, customer);
}
// Item added in cache successfully
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 An Object With Expiration
Note
This feature is also available in NCache Professional.
You can add data with metadata to the cache by encapsulating it in the NCache CacheItem
class.
The following example adds a basic CacheItem
containing the Customer object into the cache. Additional properties will be set against the CacheItem
in successive chapters.
// Get customer from database if not found in cache
if (customer == null)
{
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// You can use CacheItem object to add metadata along with data to cache
// CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
CacheItem customerCacheItem = new CacheItem(customer);
customerCacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
cache.Add(customerKey, customerCacheItem);
}
Add Bulk Items To Cache Data
Note
This feature is also available in NCache Professional.
AddBulk
adds an array of CacheItem
to the cache with the corresponding cache keys. This method returns a dictionary of all the keys that failed to add, along with the failure reason.
Note
For any keys that fail to add, the failure reason will be returned as an IDictionary
.
The following code adds a bulk of product items to the cache. If there are any keys that failed to add, the keys can be handled according to your business needs.
// Create an array of all Customer Keys
String[] keys = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Get items from cache
IDictionary<string, CacheItem> itemsFetched = cache.GetCacheItemBulk(keys);
// Fetch items from DB which do not exist in Cache
if (itemsFetched.Count < keys.Length)
{
//Create dictionary of items to be added to cache
IDictionary<string, CacheItem> missingItems = new Dictionary<string, CacheItem>();
foreach (string key in keys)
{
if (!itemsFetched.ContainsKey(key))
{
Customer customer = FetchCustomerFromDB(key);
CacheItem cacheItem = new CacheItem(customer);
missingItems.Add(key, cacheItem);
}
}
// Add bulk items to Cache
IDictionary<string, Exception> keysFailedToAdd = cache.AddBulk(missingItems);
if (keysFailedToAdd.Count > 0)
{
foreach( KeyValuePair<string,Exception> keyFailedToAdd in keysFailedToAdd)
Console.WriteLine($"Could not add Item {keyFailedToAdd.Key} in cache due to error : {keyFailedToAdd.Value}");
}
}
Add Objects with Asynchronous API
AddAsync
adds an item to the cache asynchronously and returns an object of the Task class which can be further used according to the business needs of the client application.
if (customer == null)
{
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
//Adding item asynchronously.You can also add data by creating a CacheItem object which stores meta data as well
Task<CacheItemVersion> task = cache.AddAsync(customerKey, customer);
//This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get CacheItemVersion object from task result
CacheItemVersion version = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been added to cache with verion {version.Version}.");
}
}
Using ICache.Add for Distributed Locking
Due to its versatile nature, another wide use of Add operation is in locking the cache if it is being used by multiple applications.
For example, an environment is set such that as soon as any application connects to the cache, it adds a specific key that is known to all applications. And once the application is done using the cache, it removes the key from the cache. If the key is added successfully, it can proceed to use the cache according to its logic. However, if the key already exists, it means the cache is already being used by an application and is "locked".
This is described in steps in the following diagram:
App A and App B add the "WorkStarted" key as soon as the application is started.
The key passed by App A is added to the cache before the one passed by App B.
App B gets a "The specified key already exists" exception. In this scenario, App B will wait for App A to finish its work, i.e., until it can successfully add the "WorkStarted" key.
App A removes the key from the cache once done with its work.
App B adds the key to the cache again.
The key is added by App B successfully, locking the cache for other applications.
Additional Resources
NCache provides the sample application for Basic Operations on GitHub.
See Also
.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Node.js: Cache class.
Python: ncache.client class.