Update/Insert Data in Cache
NCache provides the linearly scalable Insert method and its overloads to support high-performance data updates. This API guarantees data consistency by overwriting existing items or atomically adding new entries if the key does not exist. By using Insert, applications reduce network serialization overhead and improve overall system throughput.
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, CacheItemVersion, CacheItem, Insert.
- 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, CacheItemVersion, CacheItem, insert.
- 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, insert.
- 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, CacheItemVersion, CacheItem, insert.
- 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.
How to Update Object in Cache
The Insert method is the standard approach for basic synchronization between your application layer and the distributed store. You can update a custom object in the cache using various overloads of the Insert method. This returns a CacheItemVersion.
Important
- If the key already exists, it will overwrite the existing cache item with the same key.
- If the key does not exist, the operation adds the item to the cache instead.
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following example gets the values of an existing object and inserts it against the same key into the cache. If the key does not exist, it adds it to the cache.
try
{
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Get updated customer from database against given customer key
Customer customer = FetchCustomerFromDB(customerKey);
// Insert Customer object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);
// Item updated in cache successfully
}
catch (OperationFailedException ex)
{
// 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 updated product from database against given product ID
Product product = fetchProductFromDB(1001);
// Insert Product object to cache
CacheItemVersion version = cache.insert("1001", product);
// Item updated in cache successfully
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like IllegalArgumentException or NullPointerException
}
try:
# Precondition: Cache is already connected
# Get updated 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()
# Insert Product object to cache
version = cache.insert(key, product)
# Item updated in cache successfully
except Exception as error:
# Exception can occur due to:
# Connection Failures
# Operation Timeout
# Operation performed during state transfer
print(f"An error occurred: {error}")
try
{
// Precondition: Cache is already connected
//Get updated 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();
// Insert Product object to cache
var version = await this.cache.insert(key, product);
// Item updated in cache successfully
}
catch(error)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
// Using NCache Enterprise 4.9.1
try
{
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Get updated customer from database against given customer key
Customer customer = FetchCustomerFromDB(customerKey);
// Insert Customer object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);
// Item updated in cache successfully
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
How to Update Object With Expiration
CacheItem is a custom class provided by NCache that can be used to add data to the cache and also lets you set additional specifications associated with an object as properties of this class.
The CacheItem is updated in the cache against a unique key. By assigning expiration policies to a CacheItem, the cache enables automated memory management, preventing any outdated or stale data from persisting in the cache.
Important
- If the key already exists, it will overwrite the existing cache item with the same key.
- If the key does not exist, the operation adds the item to the cache instead.
The following example gets updated values of an existing CacheItem and inserts it against the same key into the cache. If the key does not exist, it adds it to the cache.
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Get the customer from the database
Customer customer = FetchCustomerFromDB(customerKey);
// Update Customer's Phone
customer.Phone = "0921-12 34 65";
// Create CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
// Update customer in DB and Cache
if (UpdateDB(customer))
{
cache.Insert(customerKey, cacheItem);
}
// Precondition: Cache is already connected
String customerKey = "ALFKI";
// Get the customer from the database
Customer customer = fetchCustomerFromDB(customerKey);
// Update Customer's Phone
customer.setPhone("0921-12 34 65");
// Create CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));
// Update customer in DB and Cache
cache.insert(customerKey, cacheItem);
# Precondition: Cache is already connected
# Get the customer from the database
product = fetch_product_from_db()
# 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)
# Insert CacheItem to cache
version = cache.insert(key, cache_item)
// Precondition: Cache is already connected
// Get the customer from the database
product = await this.fetchProductFromDB();
// 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);
// Insert CacheItem to cache
var version = await this.cache.insert(key,cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Get the customer from the database
Customer customer = FetchCustomerFromDB(customerKey);
// Update Customer's Phone
customer.CustomerPhone = "0921-12 34 65";
CacheItem cacheItem = new CacheItem(customer);
cache.Insert(customerKey, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);
Additional Resources
NCache provides a 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.