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
Add Object to Cache
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 Product class and its associated key into the cache. This returns CacheItemVersion
. The code sample then checks whether the key has been successfully added to the cache or not.
Tip
One quick way to verify whether an item has been added is to use either of the following property 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
// Pre-condition: Cache is already connected
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
// Add Product object to cache
CacheItemVersion version = cache.add(key, product);
// Item added in cache successfully
// Pre-condition: Cache is already connected
// Get product from database against given product ID
val product = fetchProductFromDB(1001)
// Generate a unique cache key for this product
val key = "Product:" + product.getProductId
// Add Product object to cache
val version = cache.add(key, product)
// Item added in cache successfully
// This is an async method
// Pre-condition: Cache is already connected
// Get product from database against given product ID
product = await this.fetchProductFromDB(1001);
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Add Product object to cache
var version = await this.cache.add(key, product);
// Item added in cache successfully
# Pre-condition: Cache is already connected
# Get product from database against given product ID
product = fetch_product_from_db(1001)
# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()
# Add Product object to cache
version = cache.add(key, product)
# 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
You can add data with metadata to the cache by encapsulating it in 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);
}
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
// You can OPTIONALLY specify multiple properties e.g. Priority, Expiration
// These properties are explained in successive chapters
CacheItem cacheItem = new CacheItem(product);
// Add CacheItem to cache
CacheItemVersion version = cache.add(key, cacheItem);
// Get product from database against given product ID
val product = fetchProductFromDB(1001)
// Generate a unique cache key for this product
val key = "Product:" + product.getProductId
// You can OPTIONALLY specify multiple properties e.g. Priority, DataExpiration
// These properties are explained in successive chapters
val cacheItem = new CacheItem(product)
// Add CacheItem to cache
val version = cache.add(key, cacheItem)
// This is an async method
// Get product from database against given product ID
product = await this.fetchProductFromDB(1001);
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Create a new CacheItem for this product
// You can OPTIONALLY specify multiple properties e.g. Priority, Expiration
// These properties are explained in successive chapters
var cacheItem = new ncache.CacheItem(product);
// Add CacheItem to cache
var version = await this.cache.add(key,cacheItem);
# Get product from database against given product ID
product = fetch_product_from_db(1001)
# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()
# Create a new CacheItem for this product
# You can OPTIONALLY specify multiple properties e.g.Priority, Expiration
# These properties are explained in successive chapters
cache_item = ncache.CacheItem(product)
# Add CacheItem to cache
version = cache.add(key, cache_item)
except Exception as exp:
# Handle errors
Add JsonObject To Cache
Note
This feature is only available in NCache Enterprise Edition.
JsonObject
is a class that represents JObject in JSON standards in NCache's domain. You can add attributes to the JsonObject
using the AddAttribute
method where you have to specify an attribute name and a value as JsonValue or JsonValueBase
. Attribute name is case sensitive and cannot be redundant and in case of redundant attributes, exception is thrown.
Note
In order to use JsonValueBase
, please add the following namespace in your application:
Alachisoft.NCache.Runtime.JSON
The example below creates a JsonObject
customer along with the attributes and then adds it to the cache.
// Get customer from database if not found in cache
if (customer == null)
{
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// Create a new JSON object and set attributes
JsonObject jsonCustomer = new JsonObject();
jsonCustomer.AddAttribute("CustomerID", (JsonValue)customer.CustomerID);
jsonCustomer.AddAttribute("ContactName", (JsonValue)customer.ContactName);
jsonCustomer.AddAttribute("CompanyName", (JsonValue)customer.CompanyName);
jsonCustomer.AddAttribute("Phone", (JsonValue)customer.Phone);
jsonCustomer.AddAttribute("Address", (JsonValue)customer.Address);
cache.Add(customerKey, jsonCustomer);
}
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Create a unique key for the object
String key = "Product:" + product.getProductID();
// Create a new JSON object and set attributes
// string values need to be added with JsonValue
JsonObject jsonProduct = new JsonObject();
jsonProduct.addAttribute("ProductID", new JsonValue(product.getProductID()));
jsonProduct.addAttribute("ProductName", new JsonValue(product.getProductName()));
jsonProduct.addAttribute("Category", new JsonValue(product.getCategory()));
jsonProduct.addAttribute("UnitPrice", new JsonValue(product.getPrice()));
jsonProduct.addAttribute("UnitsInStock", new JsonValue(product.getUnitsAvailable()));
// Create a new CacheItem for product and then insert
CacheItem cacheItem = new CacheItem(jsonProduct);
// Add object in the cache with the key
cache.add(key, cacheItem);
// JsonObject will successfully be added to the cache
// Get product from database against given product ID
val product = fetchProductFromDB(1001)
// Create a unique key for the object
val key = "Product:" + product.getProductID
// Create a new JSON object and set attributes
// string values need to be added with JsonValue
val jsonProduct = new JsonObject()
jsonProduct.addAttribute("ProductID", new JsonValue(product.getProductID))
jsonProduct.addAttribute("ProductName", new JsonValue(product.getProductName))
jsonProduct.addAttribute("Category", new JsonValue(product.getCategory))
jsonProduct.addAttribute("UnitPrice", new JsonValue(product.getPrice))
jsonProduct.addAttribute("UnitsInStock", new JsonValue(product.getUnitsAvailable))
// Create a new CacheItem for product and then insert
val cacheItem = new CacheItem(jsonProduct)
// Add object in the cache with the key
cache.add(key, cacheItem)
// JsonObject will successfully be added to the cache
Add Bulk Items To Cache
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}");
}
}
// Fetch all products from database
Product[] products = fetchProductsfromdb();
//Create Map of items to be added to cache
java.util.Map<String, CacheItem> itemsMap = new java.util.HashMap<String, CacheItem>();
for (Product product : products)
{
String key = "Product:" + product.getProductID();
CacheItem cacheItem = new CacheItem(product);
//Add Map to cache
itemsMap.put(key, cacheItem);
}
// Add bulk data
java.util.Map<String, Exception> keysFailedToAdd = cache.addBulk(itemsMap);
//Check if keys failed to add
if (keysFailedToAdd.size() > 0)
{
for (java.util.Map.Entry<String, Exception> entry : keysFailedToAdd.entrySet())
{
// Check failure reason
if (entry.getValue() instanceof OperationFailedException)
{
OperationFailedException exception = (OperationFailedException) entry.getValue();
if (exception.getErrorCode() == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// An item with the same key already exists
}
}
else
{
// Any other exception
}
}
}
// Fetch all products from database
var products = fetchProductFromDB
//Create Map of items to be added to cache
var itemsMap: Map[String, CacheItem] = Map()
for (product <- products) {
var key = "Product:" + product.getProductId
var cacheItem = CacheItem(product)
//Add Map to cache
itemsMap = itemsMap + (key -> cacheItem)
}
// Add bulk data
var keysFailedToAdd = cache.addBulk(itemsMap)
//Check if keys failed to add
if (keysFailedToAdd.nonEmpty) {
for (entry <- keysFailedToAdd) {
// Check failure reason
}
}
// This is an async method
// Fetch all products from database
var products = await this.fetchProductFromDB();
//Create map of items to be added to cache
var dictionary = new map();
products.forEach(prod => {
var key = "Product:" + this.product.getProductID();
var cacheItem = new ncache.CacheItem(prod);
//Add items to dictionary
dictionary.set(key,cacheItem);
});
var keysFailedToAdd = this.cache.addBulk(dictionary);
if(keysFailedToAdd.size() > 0)
{
keysFailedToAdd.forEach(entry => {
if(entry.getValue() == false)
{
var value = false;
}
else
{
// Any other exception
}
});
}
# Fetch all products from database
products = fetch_products_from_db()
# Create map of items to be added to cache
dictionary = {}
for product in products:
key = "Product:" + product.get_product_id()
cache_item = ncache.CacheItem(product)
# Add items to dictionary
dictionary[key] = cache_item
keys_failed_to_add = cache.add_bulk(dictionary)
if len(keys_failed_to_add) > 0:
for entry in keys_failed_to_add:
if not keys_failed_to_add[entry]:
value = False
else:
# Any other exception
value = True
Add Objects with Asynchronous API
Note
This feature is only available in NCache Enterprise Edition.
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}.");
}
}
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);
// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
// Add Product object to cache
FutureTask<CacheItemVersion> task = cache.addAsync(key, product);
//This task object can be used as per your business needs
if (task.isDone())
{
// Task completed
}
// Get product from database against given product ID
val product = fetchProductFromDB(1001)
// Generate a unique cache key for this product
val key = "Product:" + product.getProductId
// Add Product object to cache
val task = cache.addAsync(key, product)
//This task object can be used as per your business needs
if (task.isCompleted) {
// Task completed
}
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product string
key = f"Product:1001"
# Add Product object to cache asynchronously
async def add_async():
task = cache.add_async("key", "product")
value = await task
asyncio.run(add_async())
# This task object can be used as per your business needs
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 which 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 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
Data Structures in Cache
JSON Data in cache
Update Existing Data in Cache
Retrieve Existing Cache Data
Remove Data from Cache
How to Connect to Cache