• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

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

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
  • Install either of the following NuGet packages in your application based on your NCahce edition:
    • Enterprise: Alachisoft.NCache.SDK
    • Professional: Alachisoft.NCache.Professional.SDK
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Exceptions
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • For API details refer to: ICache, Add, Insert, CacheItem , CacheItemVersion, Count, Contains, AddBulk(), AddAsync()
  • To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Add the following Maven dependencies in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise Edition--> 
    <artifactId>ncache-client</artifactId>
    <!--for NCache Professional Edition-->
    <artifactId>ncache-professional-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your application:
    • import com.alachisoft.ncache.runtime.exceptions.*;
    • import com.alachisoft.ncache.client.*;
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • For API details refer to: Cache, add, insert, CacheItem, CacheItemVersion, getCount, addBulk(), addAsync()
  • To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Install and include either of the following modules in your application based on your NCache edition:
    • Enterprise: const ncache = require('ncache-client')
    • Professional: const ncache = require('ncache-professional-client')
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details refer to: Cache, CacheItem, CacheItemVersion, add, insert
  • To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Install the NCache Python client by executing the following command:
# Enterprise Client
pip install ncache-client

# Professional Client
pip install ncache-professional-client
  • Import the NCache module and asyncio in your application.
  • Cache must be running.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Add the following Maven dependencies in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise Edition--> 
    <artifactId>ncache-scala-client</artifactId>
    <!--for NCache Professional Edition-->
    <artifactId>ncache-scala-professional-client</artifactId> 
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your application:
    • import com.alachisoft.ncache.scala.client.*;
  • Cache must be running.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.

Custom Object

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.
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try
{
    // 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.ProductID}";

    // Add Product object to cache
    CacheItemVersion version = cache.Add(key, product);

    // 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
{
    // 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
}
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
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    product = await this.fetchProductFromDB();

    // 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
}
try:
    # Pre-condition: Cache is already connected

    # Get product from database against given product ID
    product = fetch_product_from_db()

    # 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 exp:
    # Handle errors
try {
    // 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
}
catch {
    case exception: Exception =>
    // Handle any errors
}

CacheItem

You can add data with metadata to the cache by encapsulating it in NCache CacheItem class.

Warning

If the key already exists, "The specified key already exists" exception will be thrown.

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.

The following example adds a basic CacheItem containing the Product object into the cache. Additional properties will be set against the CacheItem in successive chapters.

Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try 
{
    // 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.ProductID}";

    // 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 CacheItem(product);

    // Add CacheItem to cache
    CacheItemVersion version = cache.Add(key, cacheItem);
}
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 
{
    // 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();

    // 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);
} 
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
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    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);

    // Add CacheItem to cache       
    var version = await this.cache.add(key,cacheItem);
}
catch(error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected

    # Get product from database against given product ID
    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)

    # Add CacheItem to cache
    version = cache.add(key, cache_item)
except Exception as exp:
    # Handle errors
try {
    // 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

    // 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)
}
catch {
    case exception: Exception =>
    // Handle any errors
}

CacheItem with Location Affinity

Note

This feature is only available in NCache Enterprise Edition.

You can also add a cache item using NCache Location Affinity syntax. Location Affinity will store the CacheItem created with an identical key at the same node so that when the data is fetched from the cache, the extra matching cost is saved.

Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try 
{
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    Product product = FetchProductFromDB(1001);

    // Unique product key for this product
    string productKey = "Product:1001";

    // Create a new CacheItem for this product
    var productCacheItem = new CacheItem(product);

    // Add CacheItem to cache
    CacheItemVersion version = cache.Add(productKey, productCacheItem);

    // Get order from database against given order ID
    Order order = FetchOrderFromDB(17);

    // Unique order key for this order using Location Affinity syntax
    // This will create an affinity for this orderKey with the respective productKey
    string orderKey = "Order_{Product:1001}";

    var orderCacheItem = new CacheItem(order);

    // Add order with Location Affinity to cache
    CacheItemVersion version = cache.Add(orderKey, orderCacheItem);

}
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
{
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    Product product = fetchProductFromDB(1001);

    // Unique product key for this product
    String productKey = "Product:1001";

    // Create a new CacheItem for this product
    CacheItem productCacheItem = new CacheItem(product);

    // Add CacheItem to cache
    CacheItemVersion version = cache.add(productKey, productCacheItem);

    // Get order from database against given order ID
    Order order = fetchOrderFromDB(17);

    // Unique order key for this order using Location Affinity syntax
    // This will create an affinity for this orderKey with the respective productKey
    String orderKey = "Order_{" + productKey + "}";

    CacheItem orderCacheItem = new CacheItem(order);

    // Add order with Location Affinity to cache
    CacheItemVersion cacheItemVersion = cache.add(orderKey, orderCacheItem);

}
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
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    product = await this.fetchProductFromDB();

    // Generate a unique cache key for this product
    var productKey = "Product:1001";

    // Create a new CacheItem for this product
    var productCacheItem = new ncache.CacheItem(product);

    // Add CacheItem to cache
    var version = await this.cache.add(productKey, productCacheItem);

    // Get order from database against given order ID
    var order = this.fetchOrderFromDB(17);

    // Unique order key for this order using Location Affinity syntax
    // This will create an affinity for this orderKey with the respective productKey
    var orderKey = "Order_{" + productKey + "}";

    var orderCacheItem = new ncache.CacheItem(order);

    // Add order with Location Affinity to cache
    var cacheItemVersion = await this.cache.add(orderKey, orderCacheItem);
}
catch(error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected

    # Get product from database against given product ID
    product = fetch_product_from_db()

    # Generate a unique cache key for this product
    product_key = "Product:" + product.get_product_id()

    # Create a new CacheItem for this product
    product_cache_item = ncache.CacheItem(product)

    # Add CacheItem to cache
    version = cache.add(product_key, product_cache_item)

    # Get order from database
    order = fetch_order_from_db()

    # Unique order key for this order using Location Affinity syntax
    # This will create an affinity for this order_key with the respective product_key
    order_key = "Order_{" + product_key + "}"

    order_cache_item = ncache.CacheItem(order)

    # Add order with Location Affinity to cache
    cache_item_version = cache.add(order_key, order_cache_item)
except Exception as exp:
    # Handle errors
try {
    // Pre-condition: Cache is already connected

    // Get product from database against given product ID
    val product = fetchProductFromDB(1001)

    // Unique product key for this product
    val productKey = "Product:1001"

    // Create a new CacheItem for this product
    val productCacheItem = new CacheItem(product)

    // Add CacheItem to cache
    val version = cache.add(productKey, productCacheItem)

    // Get order from database against given order ID
    val order = fetchOrderFromDB(17)

    // Unique order key for this order using Location Affinity syntax
    // This will create an affinity for this orderKey with the respective productKey
    val orderKey = "Order_{" + productKey + "}"

    val orderCacheItem = new CacheItem(order)

    // Add order with Location Affinity to cache
    val cacheItemVersion = cache.add(orderKey, orderCacheItem)
}
catch {
    case exception: Exception =>
    // Handle any errors
}

JsonObject

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 product along with the attributes and then adds it to the cache.

  • .NET/.NET Core
  • Java
  • Scala
try
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Get product from database against given product ID
    Product product = FetchProductFromDB(1001);

    // Create a unique key for the object
    string key = $"Product:{product.ProductID}";

    // Create a new JSON object and set attributes
    // string values need to be added with JsonValue
    var jsonProduct = new JsonObject();
    jsonProduct.AddAttribute("ProductID", product.ProductID);
    jsonProduct.AddAttribute("ProductName", (JsonValue)product.ProductName);
    jsonProduct.AddAttribute("Category", (JsonValue)product.Category);
    jsonProduct.AddAttribute("UnitPrice", product.UnitPrice);
    jsonProduct.AddAttribute("UnitsInStock", product.UnitsInStock);

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonProduct);

    // Add object in the cache with the key
    cache.Add(key, cacheItem);

    // JsonObject will successfully be added to the cache
}
catch (OperationFailedException ex)
{
    if (ex.ErrorCode == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
    {
        // An attribute already exists with the same name
    }
    else if (ex.ErrorCode == NCacheErrorCodes.REFERENCE_TO_SELF)
    {
        // No object can contain a reference to itself
    }
    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
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // 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
}
catch (OperationFailedException ex)
{
    if (ex.getErrorCode() == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
    {
        // An attribute already exists with the same name
    }
    else if (ex.getErrorCode() == NCacheErrorCodes.REFERENCE_TO_SELF)
    {
        // No object can contain a reference to itself
    }
    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 {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // 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
}
catch {
    case exception: Exception =>
    // Handle any errors
}

JsonArray

JsonArray represents JArray in JSON standards in NCache’s domain mapping arrays or list like collections in NCache’s domain to JArray according to JSON conventions. JsonArray is quite similar to JsonObject, with the difference of JsonObject being a key, value pair whereas JsonArray being a collection.

The values added in JsonArray can either be JsonValue, JsonObject, JsonNull or even another JsonArray; provided it is not adding itself to itself.

The following example creates a JsonArray and adds it to the cache.

  • .NET/.NET Core
  • Java
  • Scala
try
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a new JsonArray
    var jsonArray = new JsonArray();

    // Get top ten products from the data source
    Product[] products = FetchTop10Products();

    // Convert these products in JsonObjects
    foreach (Product product in products)
    {
        // Create jsonObject and set its attributes
        // ProductName is string so it needs to be added with JsonValue
        var jsonProduct = new JsonObject();
        jsonProduct.AddAttribute("ProductID", product.ProductID);
        jsonProduct.AddAttribute("ProductName", (JsonValue)product.ProductName);
        jsonProduct.AddAttribute("Category", (JsonValue)product.Category);
        jsonProduct.AddAttribute("UnitPrice", product.UnitPrice);
        jsonProduct.AddAttribute("UnitsInStock", product.UnitsInStock);

        // Add jsonObjects to the jsonArray
        jsonArray.Add(jsonProduct);
    }
    // Create a unique key for the array
    string key = "Products";

    // Create a new CacheItem for product and then insert
    var cacheItem = new CacheItem(jsonArray);

    // Add the array in the cache with the key
    cache.Add(key, cacheItem);

}
catch(OperationFailedException ex)
{
    if (ex.ErrorCode == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
    {
        // An attribute already exists with the same name
    }
    else if (ex.ErrorCode == NCacheErrorCodes.REFERENCE_TO_SELF)
    {
        // No object can contain a reference to itself
    }
    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
{
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a new JsonArray
    var jsonArray = new JsonArray();

    // Get top ten products from the data source
    Product[] products = fetchTop10Products();

    // Convert these products in JsonObjects
    for (Product product: products) 
    {
        // Create jsonObject and set its attributes
        // ProductName is string so it needs to be added with JsonValue
        var 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.getUnitPrice()));
        jsonProduct.addAttribute("UnitsInStock",new JsonValue(product.getUnitsInStock()));

        // Add jsonObjects to the jsonArray
        jsonArray.add(jsonProduct);
    }

    // Create a unique key for the array
    String key = "Products";

    // Create a new CacheItem for product and then insert
    CacheItem cacheItem = new CacheItem(jsonArray);

    // Add array in the cache with key
    cache.add(key, cacheItem);

}
catch (OperationFailedException ex)
{
    if(ex.getErrorCode() == NCacheErrorCodes.ATTRIBUTE_ALREADY_EXISTS)
    {
        // An attribute already exists with the same name
    }
    else if (ex.getErrorCode() == NCacheErrorCodes.REFERENCE_TO_SELF)
    {
        // No object can contain a reference to itself
    }
    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 {
    // Pre-Condition: Cache is already connected
    // Cache is JSON serialized

    // Create a new JsonArray
    val jsonArray = new JsonArray()

    // Get top ten products from the data source
    val products = fetchTop10Products

    // Convert these products in JsonObjects
    for (product <- products)
    {
        // Create jsonObject and set its attributes
        // ProductName is string so it needs 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.getUnitPrice))
        jsonProduct.addAttribute("UnitsInStock",new JsonValue(product.getUnitsInStock))

        // Add jsonObjects to the jsonArray
        jsonArray.add(jsonProduct)
    }

    // Create a unique key for the array
    val key = "Products"

    // Create a new CacheItem for product and then insert
    val cacheItem = new CacheItem(jsonArray)

    // Add array in the cache with key
    cache.add(key, cacheItem)
}
catch {
    case exception: Exception =>
    // Handle any errors
}

Bulk Items

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.

Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try
{
    // Pre-condition: Cache is already connected

    // Fetch all products from database
    Product[] products = FetchProductsFromDB();

    //Create dictionary of items to be added to cache
    IDictionary<string, CacheItem> dictionary = new Dictionary<string, CacheItem>();

    foreach (var prod in products)
    {
        string key = $"Product:{prod.ProductID}";
        var cacheItem = new CacheItem(prod);

        //Add dictionary to cache
        dictionary.Add(key, cacheItem);
    }

    // Add bulk data
    IDictionary<string, Exception> keysFailedToAdd = cache.AddBulk(dictionary);

    //Check if keys failed to add
    if (keysFailedToAdd.Count > 0)
    {
        foreach (KeyValuePair<string, Exception> entry in keysFailedToAdd)
        {
            // Check failure reason
            if (entry.Value is OperationFailedException)
            {
                var exception = entry.Value as OperationFailedException;

                if(exception.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
                {
                    // An item with the same key already exists
                }
            }
            else
            {
                // Any other exception
            }
        }
    }
}
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
{
    // Pre-condition: Cache is already connected

    // Fetch all products from database
    Product[] products = fetchProducts();

    //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
            }
        }
    }
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
   // Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // 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
            }
        });
    }
}
catch(error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected

    # 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
except Exception as exp:
    # Handle errors
try {
    // Pre-condition: Cache is already connected

    // Fetch all products from database
    var products = fetchProducts

    //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
      }
    }
}
catch {
    case exception: Exception =>
    // Handle any errors
}

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.

  • .NET/.NET Core
  • Java
  • Python
  • Scala
try 
{
    // 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.ProductID}";

    // Add Product object to cache
    Task task = cache.AddAsync(key, product);

    //This task object can be used as per your business needs
    if (task.IsFaulted)
    {
        // Task completed due to an unhandled exception
    }
}
catch (OperationFailedException ex)     
{
    // NCache specific exception
    // Exception can occur due to Connection Failure
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try
{
    // 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
    FutureTask<CacheItemVersion> task = cache.addAsync(key, product);

    //This task object can be used as per your business needs
    if (task.isDone())
    {
        // Task completed 
    }
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    // Exception can occur due to Connection Failure
}
catch (Exception ex)
{
  // Any generic exception like NullPointerException or IllegalArgumentException
}
try:
    # Pre-condition: Cache is already connected

    # Get product from database
    product = fetch_product_from_db()

    # Generate a unique cache key for this product string
    key = f"Product:{product.get_product_id()}"

    # 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
except Exception as exp:
    # Handle any exception
try {
    // 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 task = cache.addAsync(key, product)

    //This task object can be used as per your business needs
    if (task.isCompleted) {
      // Task completed
    }
}
catch {
    case exception: Exception =>
    // Handle any errors
}

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:

Add Data to Cache

  1. App A and App B add the "WorkStarted" key as soon as the cache is started.

  2. The key passed by App A is added to the cache before the one passed by App B.

  3. 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.

  4. App A removes the key from the cache once done with its work.

  5. App B adds the key to cache again.

  6. 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

Back to top Copyright © 2017 Alachisoft