Retrieve Cache Data
NCache uses a linearly scalable high-performance key-value store architecture to enable low-latency data retrieval from distributed environments. By using unique keys, you can retrieve a custom object, CacheItem, or bulk items from the cache. NCache provides optimized APIs for data retrieval based on the specified key to minimize network overhead and maximize application throughput.
Prerequisites
Before using the NCache Client-side APIs, ensure that the following prerequisites are fulfilled:
- Install the following NuGet packages in your .NET client application:
- Include the following namespaces in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: ICache, CacheItem, GetCacheItem, Get.
- Add the following Maven dependencies for your Java client application in
pom.xml file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Import the following packages in your Java client application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, CacheItem, getCacheItem, get.
- Install the following packages in your Python client application:
- Import the following packages in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, CacheItem, get, get_cacheitem.
- Install and include the following module in your Node.js client application:
- Include the following class in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, CacheItem, getCacheItem, get.
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Create a new Console Application.
- Make sure that the data being added is serializable.
- Add NCache References by locating
%NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
- Include the
Alachisoft.NCache.Web.Caching namespace in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
How to Retrieve Object from Cache
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, enabling fast, key-based retrieval of cached data in distributed applications. The Get method is the most direct way to retrieve data when only the value is required, delivering minimal computational overhead for simple read operations.
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.
try
{
// Precondition: Cache is already connected
string customerKey = "Customer:ALFKI";
// Retrieve the Customer object
Customer customer = cache.Get<Customer>(customerKey);
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
try
{
// Precondition: Cache is already connected
String customerKey = "ALFKI";
// Retrieve the Customer object
Customer customer = cache.get(customerKey, Customer.class);
System.out.println("Customer with key " + customerKey + " has value " + customer);
}
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:
# 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)
# Insert item into cache
cache.insert(key, cache_item)
# Retrieve the Customer object
retrieved_item = cache.get(key, Product)
# Perform your logic
print("Item received")
except Exception as error:
print("An error occurred:", str(error))
try
{
// 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);
// Retrieve the Customer object
var retrievedItem = await this.cache.get(key, Product);
}
catch(error)
{
// Handle errors
}
// Using NCache Enterprise 4.9.1
try
{
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// Retrieve the Customer object
object result = cache.Get(customerKey);
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
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
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
How to Retrieve CacheItem from Cache
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. Using GetCacheItem is recommended when your application logic requires metadata (such as Tags, Expiration, or Versioning) alongside the actual cached value.
The following example retrieves an existing CacheItem with specified key and checks if the result is of Customer type and type casts it accordingly.
// Precondition: Cache is already connected
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}");
}
// Precondition: Cache is already connected
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());
}
# Precondition: 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")
// Precondition: Cache is already connected
// 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
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Retrieve the CacheItem
CacheItem retrievedCacheItem = cache.GetCacheItem(customerKey);
if (retrievedCacheItem != null)
{
Customer customer = (Customer)retrievedCacheItem.Value;
Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
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.