Retrieve Existing Cache Data
While NCache also supports querying the cache, it utilizes the key-value architecture of its store to maximize the ways of data retrieval. You can retrieve a custom object, CacheItem, or bulk items from the cache using the unique key associated with the item. NCache provides various overloads of Get()
method to fetch items from the cache based on the specified key.
Prerequisites
- Install either of the following NuGet packages in your application based on your NCache edition:
- 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.
- For API details refer to: ICache, CacheItem, GetCacheItem(), Get, GetList, GetBulk(), GetCacheItemBulk
- 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.datastructures.*;
import com.alachisoft.ncache.runtime.json.*;
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,CacheItem, getCacheItem(), get, getList, getBulk()
- 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, getCacheItem, get(), getList, getBulk()
- 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 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.*;
import com.alachisoft.ncache.scala.client.datastructures*;
- 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 fetch a custom object from the cache using various overloads of the Get()
method by specifying the key of the cache item. The object is retrieved as a template, so it needs to be type-cast accordingly if it is a custom class object.
Important
If the key does not exist in the cache, null value is returned.
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 fetches an existing item of Product class with the specified key. Keep in mind that Get
returns a template which needs to be cast accordingly, so the object is cast to Product
type in this example. If the specified key does not exist in cache, null value is returned.
try
{
// Pre-condition: Cache is already connected
// Get key to fetch from cache
string key = $"Product:{product.ProductID}";
// Get item against key from cache in template type
var retrievedItem = cache.Get<Product>(key);
if (retrievedItem != null)
{
if (retrievedItem is Product)
{
// Perform operations according to business logic
}
}
else
{
// Null returned; no key exists
}
}
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
// Get Product from database against given ProductID
Product product = fetchProductFromDB(1001);
// Get key to fetch from cache
String key = "Product:" + product.getProductID();
// Create a CacheItem
var cacheItem = new CacheItem(product);
cache.insert(key , cacheItem);
// Get item against key from cache in given Class type
Product retrievedItem = cache.get(key, Product.class);
if (retrievedItem != null)
{
// Perform operations according to your business logic
}
else
{
// Null returned; no key exists
}
}
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
// Get Product from database against given ProductID
var product = this.fetchProductFromDB(1001);
// Get key to fetch from cache
var key = "Product:" + this.product.getProductID();
// Create a CacheItem
var cacheItem = new ncache.CacheItem(product);
await this.cache.insert(key , cacheItem);
// Get item against key from cache in given Class type
var retrievedItem = await this.cache.get(key, Product);
if (retrievedItem != null)
{
// Perform your logic
}
else
{
// Null returned; no key exists
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-condition: Cache is already connected
# Get Product from database against given ProductID
product = fetch_product_from_db()
# Get key to fetch from cache
key = "Product:" + product.get_product_id()
# Create a CacheItem
cache_item = ncache.CacheItem(product)
cache.insert(key, cache_item)
# Get item against key from cache in given Class type
retrieved_item = cache.get(key, Product)
if retrieved_item is not None:
# Perform your logic
print("Item received")
else:
# Null returned; no key exists
print("Key does not exist")
except Exception as exp:
# Handle errors
try {
// Pre-condition: Cache is already connected
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Get key to fetch from cache
val key = "Product:" + product.getProductId
// Create a CacheItem
val cacheItem = new CacheItem(product)
cache.insert(key, cacheItem)
// Get item against key from cache in given Class type
val retrievedItem = cache.get(key, classOf[Product])
if (retrievedItem != null) {
// Perform operations according to your business logic
}
else {
// Null returned; no key exists
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
CacheItem
NCache allows retrieving an existing CacheItem
from the cache using the dedicated GetCacheItem()
API. This returns a CacheItem
associated with the specified key. Its Value
property encapsulates the data.
Important
If the key does not exist in cache, null value is returned.
The following example retrieves an existing CacheItem
with specified key and checks if the result is of Product type and type casts it accordingly.
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
// Get key to fetch from cache
string key = $"Product:{product.ProductID}";
// Get CacheItem from cache
var retrievedCacheItem = cache.GetCacheItem(key);
if (retrievedCacheItem != null)
{
retrievedCacheItem.GetValue<Product>();
// Perform operations according to your business logic
}
else
{
// Null returned; key does not exist
}
}
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
// Get Product from database against given ProductID
Product product = fetchProductFromDB(1001);
// Get key to fetch from cache
String key = "Product:" + product.getProductID();
// Create a CacheItem
var cacheItem = new ncache.CacheItem(product);
cache.insert(key , cacheItem);
// Get CacheItem from cache
CacheItem retrievedCacheItem = cache.getCacheItem(key);
if (retrievedCacheItem != null)
{
retrievedCacheItem.getValue(Product.class);
// Perform operations according to your business logic
}
else
{
// Null returned; key does not exist
}
}
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
// Get key to fetch from cache
var key = "Product:" + this.product.getProductID();
// Get CacheItem from cache
var retrievedCacheItem = this.cache.getCacheItem(key);
// Get item against key from cache in given Class type
if (retrievedCacheItem != null)
{
this.cache.getValue(Product);
// Perform your logic
}
else
{
// Null returned; no key exists
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-condition: Cache is already connected
# Generate key to fetch from cache
key = "Product:1001"
# Get CacheItem from cache
retrieved_cache_item = cache.get_cacheitem(key)
# Get item against key from cache in given Class type
if retrieved_cache_item is not None:
value = retrieved_cache_item.get_value(Product)
# Perform your logic
else:
# Null returned no key exists
print("Key does not exist")
except Exception as exp:
# Handle errors
def getCacheItem(): Unit = {
try {
// Pre-condition: Cache is already connected
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Get key to fetch from cache
val key = "Product:" + product.getProductId
// Create a CacheItem
val cacheItem = CacheItem(product)
cache.insert(key, cacheItem)
// Get CacheItem from cache
val retrievedCacheItem = cache.getCacheItem(key)
if (retrievedCacheItem != null) {
retrievedCacheItem.getValue(classOf[Product])
// Perform operations according to your business logic
}
else {
// Null returned; key does not exist
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
JsonObject
Note
This feature is only available in NCache Enterprise Edition.
NCache provides the flexibility of retrieving cache data as JSON. You can either retrieve a custom object as JsonObject
or a JsonObject
as a custom object using the Get()
API, provided that the attributes represent the properties of the custom class.
You can also retrieve the attributes of a JsonObject
using the GetAttributeNames
or GetAttributeValue
method. The GetAttributeNames
method lets the user retrieve the names of the attributes of the JsonObject
in the form of a collection of strings whereas the GetAttributeValue
method retrieves the object of the JSON value against the provided attribute name.
The following example adds a custom object in the cache and retrieves it as JsonObject
.
try
{
// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Get Product from database against given ProductID
Product product = FetchProductFromDB(1001);
// Generate a unique key for this product
string key = $"product.ProductID";
// Create a CacheItem
var cacheItem = new CacheItem(product);
// Add the object with the key specified to the cache
cache.Insert(key, cacheItem);
var retrievedItem = cache.Get<JsonObject>(key);
if(retrievedItem != null)
{
// Perform operations according to business logic
}
else
{
// No such item exists
}
}
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
// Cache is JSON serialized
// Generate a unique key for this product
String key = "Product:1001";
// Create a new CacheItem for product and then insert
var cacheItem = new CacheItem(product);
// Add the object with the key specified to the cache
cache.insert(key, cacheItem);
// Retrieve the added object against the specified key
var retrievedItem = cache.get(key,JsonObject.class);
if(retrievedItem != null)
{
// Perform operations according to business logic
}
else
{
// No such item exists
}
}
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
}
try {
// Pre-Condition: Cache is already connected// Pre-Condition: Cache is already connected
// Cache is JSON serialized
// Get Product from database against given ProductID
val product = fetchProductFromDB(1001)
// Generate a unique key for this product
val key = "Product:" + product.getProductId
// Create a new JSON object and set attributes
// string values need to be added with JsonValue
val jsonProduct = JsonObject()
jsonProduct.addAttribute("ProductID", JsonValue(product.getProductId))
jsonProduct.addAttribute("ProductName", JsonValue(product.getProductName))
jsonProduct.addAttribute("Category", JsonValue(product.getCategory))
jsonProduct.addAttribute("UnitPrice", JsonValue(product.getPrice))
jsonProduct.addAttribute("UnitsInStock", JsonValue(product.getUnitsAvailable))
// Create a CacheItem
val cacheItem = client.CacheItem(jsonProduct)
// Add the object with the key specified to the cache
cache.insert(key, cacheItem)
val retrievedItem = cache.get(key, classOf[JsonObject])
if (retrievedItem != null) {
// Perform operations according to business logic
}
else {
// No such item exists
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
Bulk Items
NCache allows synchronous bulk retrieval of items in a single call to reduce network cost. Various overloads of GetBulk()
method retrieve objects from the cache for the cache keys specified. Note that the value is retrieved as a template so it needs to be type casted accordingly if it is a custom class object.
Important
- If the keys exist in the cache a dictionary of cache items and their keys is returned.
- If the key does not exist in cache, null value is returned.
The following example retrieves existing CacheItems containing objects of the Product class. The result is returned in an IDictionary
of keys and values, which can be enumerated to get the actual values of the keys. Since GetBulk
returns a template (that needs to be cast), the object is cast to Product
type in this example. If the specified key does not exist in cache, null value is returned.
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
Product[] products = FetchProductsFromDB();
// Get keys to fetch from cache
string[] keys = new string[products.Length];
int index = 0;
foreach (var product in products)
{
keys[index] = $"Product:{product.ProductID}";
index++;
}
// Get bulk from cache
IDictionary<string, Product> retrievedItems = cache.GetBulk<Product>(keys);
// Check if any keys have failed to be retrieved
if (retrievedItems.Count == keys.Length)
{
foreach (KeyValuePair<string, Product> entry in retrievedItems)
{
if (entry.Value is Product)
{
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
}
}
else
{
// Not all of the keys are present in cache
}
}
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
Product[] products = fetchProducts();
// Get keys to fetch from cache
ArrayList<String> keys = new ArrayList<>(products.length);
for (Product product : products)
{
String key = "Product:" + product.getProductID();
keys.add(key);
cache.insert(key , product);
}
// Get bulk from cache
java.util.Map<String, Product> retrievedItems = cache.<Product>getBulk(keys, Product.class);
// Check if any keys have failed to be retrieved
if (retrievedItems.size() == keys.size())
{
for (java.util.Map.Entry<String, Product> entry : retrievedItems.entrySet())
{
if (entry.getValue() != null)
{
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
}
}
else
{
// Not all of the keys are present in cache
}
}
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
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();
// Get keys to fetch from cache
var keys = [products.length];
var index = 0;
products.forEach(product => {
keys[index] ="Product:" + this.product.getProductID();
index++;
});
// Get bulk from cache
var retrievedItems = await this.cache.getBulk(keys,Product);
// Check if any keys have failed to be retrieved
if(retrievedItems.size() == keys.length)
{
retrievedItems.forEach(entry => {
if(entry.getValue() instanceof Product)
{
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
});
}
else
{
// Not all of the keys are present in cache
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-condition: Cache is already connected
# Get Products from database
products = fetch_products_from_db()
# Get keys to fetch from cache
keys = []
index = 0
for product in products:
keys.append( "Product:" + product.get_product_id())
# Get bulk from cache
retrieved_items = cache.get_bulk(keys, Product)
# Check if any keys have failed to be retrieved
if len(retrieved_items) is len(keys):
# Perform operations according to business logic
print("All the items were retrieved successfully")
else:
# Not all the keys are present in cache
print("Some of the keys were not found")
except Exception as exp:
# Handle errors
try {
// Pre-condition: Cache is already connected
val products = fetchProducts
// Get keys to fetch from cache
var keys: List[String] = List()
for (product <- products) {
val key = "Product:" + product.getProductId
keys = key :: keys
cache.insert(key, product)
}
// Get bulk from cache
val retrievedItems = cache.getBulk[Product](keys, classOf[Product])
// Check if any keys have failed to be retrieved
if (retrievedItems.size == keys.size) {
for (entry <- retrievedItems) {
// Perform operations according to business logic
}
}
else {
// Not all of the keys are present in cache
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
Bulk of CacheItem
You can also retrieve a bulk of CacheItem
using the GetCacheItemBulk()
method. Here is an example:
try
{
// Pre-condition: Cache is already connected
// Fetch a products array
Product[] products = FetchProductsFromDB();
// Get keys to fetch from cache
string[] keys = new string[products.Length];
int index = 0;
foreach (var product in products)
{
// Using the same unique cache key for this product
keys[index] = $"Product:{product.ProductID}";
index++;
}
// Retrieve items from cache in a dictionary
IDictionary<string, CacheItem> retrievedItems = cache.GetCacheItemBulk(keys);
// Check if any keys have failed to be retrieved
if (retrievedItems.Count == keys.Length)
{
foreach (KeyValuePair<string, CacheItem> entry in retrievedItems)
{
if (entry.Value is CacheItem)
{
Product prod = entry.Value.GetValue<Product>();
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
}
}
else
{
// Not all of the keys are present in cache
foreach (var key in keys)
{
if (retrievedItems.ContainsKey(key) == false)
{
// This key does not exist in cache
}
}
}
}
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 a products array
Product[] products = fetchProducts();
// Get keys to fetch from cache
ArrayList<String> keys = new ArrayList<>(products.length);
for (Product product : products)
{
String key = "Product:" + product.getProductID();
keys.add(key);
cache.insert(key , product);
}
// Retrieve items from cache in a Map
java.util.Map<String, CacheItem> retrievedItems = cache.getCacheItemBulk(keys);
// Check if any keys have failed to be retrieved
if (retrievedItems.size() == keys.size())
{
for (java.util.Map.Entry<String, CacheItem> entry : retrievedItems.entrySet())
{
if (entry.getValue() != null)
{
Product prod = entry.getValue().<Product>getValue(Product.class);
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
}
}
else
{
// Not all of the keys are present in cache
for (String key : keys)
{
if (!retrievedItems.containsKey(key))
{
// This key does not exist in cache
}
}
}
}
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
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();
// Get keys to fetch from cache
var keys = [products.length];
var index = 0;
products.forEach(product => {
keys[index] ="Product:" + this.product.getProductID();
index++;
});
// Get bulk from cache
var retrievedItems = this.cache.getCacheItemBulk(keys);
// Check if any keys have failed to be retrieved
if(retrievedItems.size() == keys.length)
{
retrievedItems.forEach(entry => {
if(entry.getValue() instanceof ncache.CacheItem)
{
var prod = entry.getValue();
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
});
}
else
{
// Not all of the keys are present in cache
keys.forEach(key => {
if(retrievedItems.containsKey(key) == false)
{
// key does not exist in cache
}
});
}
}
catch(error)
{
// Handle errors
}
try:
# Pre-condition: Cache is already connected
# Get Products from database
products = fetch_products_from_db()
# Get keys to fetch from cache
keys = []
index = 0
for product in products:
keys.append( "Product:" + product.get_product_id())
# Get bulk from cache
retrieved_items = cache.get_cacheitem_bulk(keys)
# Check if any keys have failed to be retrieved
if len(retrieved_items) is len(keys):
for item in retrieved_items:
product = retrieved_items[item].get_value(Product)
# Perform operations according to business logic
else:
# Not all the keys are present in cache
print("Some of the keys were not found")
except Exception as exp:
# Handle errors
try {
// Pre-condition: Cache is already connected
// Fetch a products array
val products = fetchProducts
// Get keys to fetch from cache
var keys: List[String] = List()
for (product <- products) {
val key = "Product:" + product.getProductId
keys = key :: keys
cache.insert(key, product)
}
// Retrieve items from cache in a Map
val retrievedItems = cache.getCacheItemBulk(keys)
// Check if any keys have failed to be retrieved
if (retrievedItems.size == keys.size) {
for (entry <- retrievedItems) {
// Perform operations according to business logic
}
}
else {
// Not all of the keys are present in cache
}
}
catch {
case exception: Exception => {
// Handle any errors
}
}
Additional Resources
NCache provides a sample application for Basic Operations on GitHub.
See Also
How to Connect to Cache
Add Data to Cache
Update Existing Data in Cache
Remove Data from Cache
Start Cache