Retrieve Existing Cache Data
Primarily, a cache is only considered as effective as its ability to retrieve 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 single 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.
For example, an e-commerce site caches its best selling products, discounted products and new arrivals. When you request to view the best selling products, the information is fetched from the cache instead of accessing the database - saving network cost and time.
Get Operation Behavior
Get is a synchronous operation.
Get returns a template type object, which needs to be casted according to your custom object.
If specified key does not exist in cache, null value is returned.
In advanced cases, if data source is configured, data will be fetched from the data source if it does not exist in cache. For more details, refer to the chapter Data Source Providers.
Pre-requisites
- Include the following namespace in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.Exceptions
- The application must be connected to cache before performing the operation.
- 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.
Custom Object
You can fetch a single 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. For Java, Get() method is used for this purpose.
Important
If the key does not exist in cache, null value is returned.
Recommendation: 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
}
CacheItem
CacheItem is a custom class provided by NCache which can be used to add data to the cache with additional properties associated with the data. The CacheItem is added to the cache against a unique key.
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. For Java, GetCacheItem() is used for this purpose.
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.
Recommendation: 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
}
JsonObject
Note
This feature is only available in NCache Enterprise Edition.
NCache lets you retrieve cache data as JSON. You can either retrieve a custom object as JsonObject
or a JsonObject as a custom object using the Get() API.
Similar to JsonObject
you can retrieve JsonArray
or JsonValue
corresponding to a key. For more detail on the topic, please refer to the Cache Data as JSON section.
The following example adds a custom object in the cache and retrieves it as JsonObject
. Similar to this you can retrieve JsonObject
as custom object by providing the type in the Get<>
method.
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";
// Add the object with the key specified to the cache
cache.Insert(key, product);
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
}
Data Structure
Note
This feature is only available in NCache Enterprise Edition.
You can fetch data structures from the cache using specific APIs for the data type. The following code fetches a list from cache using GetList, which takes a cache key as parameter. This key is the name of the list which is specified during list creation.
For more detail on supported data structures, please refer to the section Data Structures in Cache.
Note
In order to use data structures, the following additional namespaces must be added into your application:
Alachisoft.NCache.Client.DataTypes
Alachisoft.NCache.Client.DataTypes.Collections
try
{
// Pre-condition: Cache is already connected
// List with this key already exists in cache
string key = "ProductList";
// Get list and show items of list
IDistributedList<Product> retrievedList = cache.DataTypeManager
.GetList<Product>(key);
if (retrievedList != null)
{
foreach (var item in retrievedList)
{
// Perform operations
}
}
else
{
// List does not exist
}
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.ErrorCode == NCacheErrorCodes.NOT_A_LIST)
{
// The type of the corresponding item is not a list
}
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
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
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. In case of Java, getBulk() method retrieves objects from the cache.
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.
Although a bulk operation is executed as a single operation, the operation itself is treated individually in the cache. For example, if a bulk of 100 items is specified and 20 of those items do not exist in the cache, the existing 80 items will be retrieved, while nothing will be returned for those 20 objects which do not exist.
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 which needs to be casted accordingly, the object is casted to Product
type in this example. If the specified key does not exist in cache, null value is returned.
Recommendation: 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
}
CacheItems in Bulk
You can also retrieve CacheItems in bulk using 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
}
Additional Resources
NCache provides sample application for Basic Operations at:
- GitHub
- Shipped with NCache: %NCHOME%\samples\dotnet\BasicOperations
See Also
How to Connect to Cache
Add Data to Cache
Update Existing Data in Cache
Remove Data from Cache
Start Cache