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 without overwriting existing entries.
Prerequisites
Before using the NCache Client-side APIs, ensure that the following prerequisites are fulfilled:
- Install the following NuGet packages in your .NET client application:
- Include the following namespaces in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: ICache, Add, CacheItemVersion, Count, Contains.
- Add the following Maven dependencies for your Java client application in
pom.xml file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Import the following packages in your Java client application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, add, CacheItem, CacheItemVersion, getCount.
- Install the following packages in your Python client application:
- Import the following packages in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, CacheItem, CacheItemVersion, add.
- Install and include the following module in your Node.js client application:
- Include the following class in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, CacheItem, CacheItemVersion, add.
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Create a new Console Application.
- Make sure that the data being added is serializable.
- Add NCache References by locating
%NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
- Include the
Alachisoft.NCache.Web.Caching namespace in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
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 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.
try
{
// Precondition: Cache is already connected
// Get customer from database
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
cache.Add(customerKey, customer);
// Item added in cache successfully
}
catch (OperationFailedException ex)
{
// NCache specific exception
if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// An item with the same key already exists
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
try
{
// Precondition: Cache is already connected
// Get customer from database
String customerKey = "ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
// Get product from database against given product ID
cache.add(customerKey, customer);
// Item added in cache successfully
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.getErrorCode() == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// An item with the same key already exists
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like NullPointerException or IllegalArgumentException
}
try:
# Precondition: 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
except Exception as error:
# Handle errors
print(f"An error occurred: {error}")
try
{
// This is an async method
// Precondition: 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
}
catch(error)
{
// Handle errors
}
// Using NCache Enterprise 4.9.1
try
{
// 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
}
catch (OperationFailedException ex)
{
// NCache specific exception
if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// An item with the same key already exists
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
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 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.
// Precondition: Cache is already connected
// Get customer from database if not found in cache
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);
// Precondition: Cache is already connected
// Get customer from database if not found in cache
String customerKey = "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.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));
cache.add(customerKey, customerCacheItem);
# Precondition: Cache is already connected
# Get customer from database if not found in cache
customer = fetch_customer_from_db(ALFKI)
key = "Customer:" + customer.get_customer_id()
# 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
cache_item = ncache.CacheItem(customer)
version = cache.add(key, cache_item)
// Precondition: Cache is already connected
// This is an async method
// Get customer from database against given customer ID
customer = await this.fetchCustomerFromDB(ALFKI);
var key = "Customer:" + customer.getCustomerID();
// 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
var cacheItem = new ncache.CacheItem(customer);
var version = await this.cache.add(key,cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
if (customer == null)
{
// Get customer from database if not found in cache
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);
cache.Add(customerKey, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);
}
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.
Python: ncache.client class.
Node.js: Cache class.