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

Add Cache Data with Named Tags

Note

This feature is only available in NCache Enterprise Edition.

In order to associate Named Tags with any cache item, it is required to provide a list of Named Tags, each having two parameters that are key as string which is the name of the tag and value as any primitive type which is the assigned value to the key. NCache then allows you to associate your objects with these Named Tags. You can add items in the cache with named tags and then later retrieve these items from the cache using the previously added named tags.

When items are already added in the cache with certain named tags, NCache provides the user with an option of updating named tags already present in the cache.

Prerequisites

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
  • Install the following NuGet package in your application:
    • Enterprise: Alachisoft.NCache.SDK
  • Include the following namespace in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Caching
    • Alachisoft.NCache.Runtime.Exceptions
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: CacheItem, NamedTags, Insert.
  • Make sure that the data being added is serializable.
  • 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>
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Import the following packages in your application:
    • import com.alachisoft.ncache.client.*;
    • import com.alachisoft.ncache.runtime.exceptions.*;
    • import com.alachisoft.ncache.runtime.caching.NamedTagsDictionary.*;
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: CacheItem, NamedTags, insert.
  • Make sure that the data being added is serializable.
  • 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 the following module in your application:
    • Enterprise: const ncache = require('ncache-client')
  • Cache must be running.
  • The application must be connected to cache before performing the operation.
  • For API details, refer to: CacheItem, NamedTags, 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
  • Import the NCache module 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>
    <artifactId>ncache-scala-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.
  • The application must be connected to cache before performing the operation.
  • Make sure that the data being added is serializable.
  • 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 Named Tags

CacheItem is a custom class provided by NCache which can be used to add data to the cache. This class encapsulates data as its value property. CacheItem also lets you set additional specifications associated with an object as property of the NamedTags class.

In the following example Named Tags are set by assigning them as a property of CacheItem.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try
{
    // Pre-condition: Cache is already connected
    // Get product from database against given productID
    Product product = FetchProductFromDB(1001);

    // Create a unique cache key for this product
    string key = $"Products:{product.ProductID}";

    // Creating a Named Tags Dictionary
    var productNamedTag = new NamedTagsDictionary();

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the instances of data, of primitive data structures. 
    productNamedTag.Add("FlashSaleDiscount", 0.5);

    // Create a new CacheItem
    var cacheItem = new CacheItem(product);

    // Setting the named tag property of the cacheitem
    cacheItem.NamedTags = productNamedTag;

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

    // CacheItem added 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 other generic exception like ArgumentNullException or ArgumentException
} 
try
{    
    // Pre-condition: Cache is already connected
    // Get product from database against given productID
    Product product = fetchProductFromDB(1001);

    // Create a unique cache key for this product
    String key = "Product:" + product.getProductID;    

    // Creating a Named Tags Dictionary
    NamedTagsDictionary productNamedTag = new NamedTagsDictionary();    

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the instances of data, of primitive data structures. 
    productNamedTag.add("FlashSaleDiscount", 0.5);

    // Create a new CacheItem
    CacheItem cacheItem = new CacheItem(product);

    // Setting the named tag property of the cacheitem
    cacheItem.setNamedTags(productNamedTag);

    // Add product object to the cache
    CacheItemVersion version = cache.add(key, cacheItem);

    // CacheItem added successfully
}
catch (OperationFailedException ex)
{
    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 IllegalArgumentException or NullPointerException        
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected
    // Get product from database against given productID
    var product = this.fetchProductFromDB(1001);

    // Create a unique cache key for this product
    var key = "Product:" + product.getProductID();

    // Creating a Named Tags Dictionary
    var productNamedTag = new ncache.NamedTagsDictionary();

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the instances of data, of primitive data structures.
    productNamedTag.add("FlashSaleDiscount", 0.5);

    // Create a new CacheItem
    // You alose need to specify the FQN(Fully Qualified Name) of the class
    var cacheItem = new ncache.CacheItem(product,"FQN.Product");

    // Setting the named tag property of the CacheItem
    cacheItem.setNamedTags(productNamedTag);

    // Add product object to the cache
    var version = await this.cache.add(key, cacheItem);

    // CacheItem added successfully
}
catch (error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected
    # Get product from database against given productID
    product = fetch_product_from_db()

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

    # Creating a Named Tags Dictionary
    product_named_tag = ncache.NamedTagsDictionary()

    # Adding Named Tags to the Dict where
    # Keys are the names of the tags as string type
    # Values are the instances of data, of primitive data structures.
    product_named_tag.add("FlashSaleDiscount", 0.5)

    # Create a new CacheItem
    cache_item = ncache.CacheItem(product)

    # Setting the named tag property of the CacheItem
    cache_item.set_named_tags(product_named_tag)

    # Add product object to the cache
    version = cache.add(key, cache_item)

    # CacheItem added successfully
except Exception as exp:
    # Handle errors
try {
    // Pre-condition: Cache is already connected

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

    // Create a unique cache key for this product
    val key = "Product:" + product.getProductId

    // Creating a Named Tags Dictionary
    val productNamedTag = NamedTagsDictionary()

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the instances of data, of primitive data structures.
    productNamedTag.add("FlashSaleDiscount", 0.5)

    // Create a new CacheItem
    val cacheItem = new CacheItem(product)

    // Setting the named tag property of the cacheItem
    cacheItem.setNamedTags(productNamedTag)

    // Add product object to the cache
    val version = cache.add(key, cacheItem)

    // CacheItem added successfully
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}

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

Update Data with Named Tags through CacheItem

Updating named tags through CacheItem requires the item to be first fetched, its named tags to be modified and then re-inserted to the cache using the Insert method.

Following example first fetches the CacheItem, creates a list with the new named tags and then re-inserts the CacheItem in the cache along with the modified named tag list. Hence, overwrites the value of existing named tags.

Warning

Providing Null named tag array will throw an ArgumentNullException.

  • .NET/.NET Core
  • Java
  • Node.js
  • Python
  • Scala
try
{   
    // Pre-condition: Cache is already connected
    // Get cache item from cache against given key
    string key = "Products:1001";
    CacheItem cacheItem = cache.GetCacheItem(key);

    // Create a Named Tags Dictionary
    var newProductNamedTag = new NamedTagsDictionary();

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the updated instances of data, of primitive data types. 
    newProductNamedTag.Add("FlashSaleDiscount", 0.7);

    // Updates the named tags with the new named tags
    // Overrides the value of the existing named tags
    cacheItem.NamedTags = newProductNamedTag;

    //Re-inserts the cacheItem into cache with modified named tags
    CacheItemVersion version = cache.Insert(key, cacheItem);

    // cacheItem is successfully added in cache with modified named tags
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures 
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any other generic exception like ArgumentNullException or ArgumentException
}
try
{
    // Pre-condition: Cache is already connected
    // Get cache item from cache against given key
    String key = "Products:1001";
    CacheItem cacheItem = cache.getCacheItem(key);

    // Create a Named Tags Dictionary
    NamedTagsDictionary newProductNamedTag = new NamedTagsDictionary();

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the updated instances of data, of primitive data types. 
    newProductNamedTag.add("FlashSaleDiscount", 0.7);

    // Updates the named tags with the new named tags
    // Overrides the value of the existing named tags
    cacheItem.setNamedTags(newProductNamedTag);

    //Re-inserts the cacheItem into cache with modified named tags
    CacheItemVersion version = cache.insert(key, cacheItem);

    // cacheItem is successfully added in cache with modified named tags
}
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 
}
// This is an async method
try 
{
    // Pre-condition: Cache is already connected
    // Get cache item from cache against given key
    var key = "Product:1001";
    var cacheItem = await this.cache.getCacheItem(key);

    // Create a Named Tags Dictionary
    var newProductNamedTag = new ncache.NamedTagsDictionary();

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the updated instances of data, of primitive data types.
    newProductNamedTag.add("FlashSaleDiscount", 0.7);

    // Updates the named tags with the new named tags
    // Overrides the value of the existing named tags
    cacheItem.setNamedTags(newProductNamedTag);

    //Re-inserts the cacheItem into cache with modified named tags
    var version = await this.cache.insert(key, cacheItem);

    // cacheItem is successfully added in cache with modified named tags

} catch (error)
{
    // Handle errors
}
try:
    # Pre-condition: Cache is already connected
    # Get cache item from cache against given key
    key = "Product:1001"
    cache_item = cache.get_cacheitem(key)

    # Create a Named Tags Dictionary
    new_product_named_tag = ncache.NamedTagsDictionary()

    # Adding Named Tags to the Dict where
    # Keys are the names of the tags as string type
    # Values are the updated instances of data, of primitive data types.
    new_product_named_tag.add("FlashSaleDiscount", 0.7)

    # Updates the named tags with the new named tags
    # Overrides the value of the existing named tags
    cache_item.set_named_tags(new_product_named_tag)

    # Re-insert the cacheItem into cache with modified named tags
    version = cache.insert(key, cache_item)

    # cacheItem is successfully added in cache with modified named tags
except Exception as exp:
    # Handle errors
try {
    // Pre-condition: Cache is already connected

    // Get cache item from cache against given key
    val key = "Products:1001"
    val cacheItem = cache.getCacheItem(key)

    // Create a Named Tags Dictionary
    val newProductNamedTag = new NamedTagsDictionary

    // Adding Named Tags to the Dictionary where
    // Keys are the names of the tags as string type
    // Values are the updated instances of data, of primitive data types.
    newProductNamedTag.add("FlashSaleDiscount", 0.7)

    // Updates the named tags with the new named tags
    // Overrides the value of the existing named tags
    cacheItem.setNamedTags(newProductNamedTag)

    //Re-inserts the cacheItem into cache with modified named tags
    val version = cache.insert(key, cacheItem)

    // cacheItem is successfully added in cache with modified named tags
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}

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

Additional Resources

NCache provides sample application for Named tags on GitHub.

See Also

Tag Cache Data
SQL Query with NamedTags
SQL Delete with NamedTags
Data Expiration

Back to top Copyright © 2017 Alachisoft