Retrieve Existing Cache Data
While NCache also supports querying the cache data, 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 the Get
method to fetch items from the cache data based on the specified key.
Prerequisites to Retrieve Existing Cache Data
Retrieve Cache Data
Note
This feature is also available in NCache Professional.
You can fetch a custom object from the cache data 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, a null value is returned.
The following example fetches an existing item of the Customer class with the specified key. Keep in mind that Get
returns a template that needs to be cast accordingly, so the object is cast to the Customer
type in this example.
// Precondition: Cache is already connected
string customerKey = "Customer:ALFKI";
// Retrieve the Customer object
Customer customer = cache.Get<Customer>(customerKey);
if (customer != null)
{
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
// Precondition: Cache is already connected
String customerKey = "ALFKI";
// Retrieve the Customer object
Customer customer = cache.get(customerKey, Customer.class);
System.out.println("Customer with key " + customerKey + " has value " + customer);
# Precondition: 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")
// Precondition: Cache is already connected
// This is an async method
// 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
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Retrieve CacheItem From Cache
Note
This feature is also available in NCache Professional.
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.
The following example retrieves an existing CacheItem
with specified key and checks if the result is of Customer type and type casts it accordingly.
string customerKey = "Customer:ALFKI";
// Retrieve the CacheItem
CacheItem retrievedCacheItem = cache.GetCacheItem(customerKey);
if (retrievedCacheItem != null)
{
Customer customer = retrievedCacheItem.GetValue<Customer>();
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
String customerKey = "ALFKI";
// Retrieve the CacheItem from cache
CacheItem retrievedCacheItem = cache.getCacheItem(customerKey);
if (retrievedCacheItem != null) {
// Get the Customer object from the CacheItem
Customer customer = retrievedCacheItem.getValue(Customer.class);
System.out.println("Customer: " + customer.getContactName() + ", Phone: " + customer.getPhone());
}
# 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")
// This is an async method
// 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
}
Retrieve Bulk Items From Cache
Note
This feature is also available in NCache Professional.
NCache allows synchronous bulk retrieval of items in a single call to reduce network costs. Various overloads of the GetBulk
method retrieve objects from the cache data for the cache keys specified. Note that the value is retrieved as a template so it needs to be type cast 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.
The following example retrieves existing CacheItems containing objects of the Customer 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 the Customer
type in this example. If the specified key does not exist in the cache, a null value is returned.
// Create an array of all keys to fetch
String[] keys = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT",
"Customer:BERGS"
};
// Get items from cache
IDictionary<string, Customer> retrievedItems = cache.GetBulk<Customer>(keys);
// Retrieve customers and their addresses from dictionary
foreach (KeyValuePair<string, Customer> retrievedItem in retrievedItems)
{
Console.WriteLine($"Customer: {retrievedItem.Value.ContactName}, Address : { retrievedItem.Value.Address}");
}
// Create an list of all keys to fetch
List<String> keys = List.of(
"Customer:ALFKI",
"Customer:ANATR",
"Customer:ANTON",
"Customer:AROUT",
"Customer:BERGS"
);
// Get items from cache
Map<String, Customer> retrievedItems = cache.getBulk(keys, Customer.class);
// Retrieve customers and their addresses from dictionary
for (Map.Entry<String, Customer> retrievedItem : retrievedItems.entrySet())
{
System.out.println("Customer: " + retrievedItem.getValue().getContactName() + ", Address: " + retrievedItem.getValue().getAddress());
}
# 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")
// This is an async method
// 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
}
Retrieve Bulk of CacheItem's From Cache
Note
This feature is also available in NCache Professional.
You can also retrieve a bulk of CacheItem
using the GetCacheItemBulk
method. Here is an example:
// Create an array of all keys to fetch
String[] keys = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT",
"Customer:BERGS"
};
// Get items from cache
IDictionary<string, Customer> retrievedItems = cache.GetBulk<Customer>(keys);
// Retrieve customers and their addresses from dictionary
foreach (KeyValuePair<string, Customer> retrievedItem in retrievedItems)
{
Console.WriteLine($"Customer: {retrievedItem.Value.ContactName}, Address : { retrievedItem.Value.Address}");
}
// 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
}
}
}
# 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")
// This is an async method
// 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
}
});
}
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.