Retrieve Data from Cache
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 general object, which needs to be cast 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 for Fetching Data
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
. - 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.
Single Item
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 general object so it needs to be type cast accordingly if it is a custom class object.
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 the Get
method returns a general object 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
object retrievedItem = cache.Get(key);
if (retrievedItem != null)
{
if (retrievedItem is Product)
{
Product product = retrievedItem as Product;
// Perform operations according to business logic
}
}
else
{
// Null returned; no key exists
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation Timeout
}
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.
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
CacheItem retrievedCacheItem = cache.GetCacheItem(key);
// If result is not null
if (retrievedCacheItem != null)
{
// If result is Product type
if (retrievedCacheItem.Value is Product)
{
Product product = retrievedCacheItem.Value as Product;
// Perform operations according to business logic
}
else
{
// Object NOT of Product type
}
}
else
{
// Null returned; key does not exist
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation Timeout
}
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 general object 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.
- 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 general object which needs to be cast accordingly, the object is cast 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
// Get keys to fetch from cache
string[] keys = new string[products.Length];
for (int i = 0; i < products.Length; i++)
{
// Using the same unique cache key for this product
keys[i] = $"Product:{products[i].ProductID}";
}
// Get bulk from cache
IDictionary retrievedItems = cache.GetBulk(keys);
// Check if any keys have failed to be retrieved
if (retrievedItems.Count == keys.Length)
{
foreach (DictionaryEntry entry in retrievedItems)
{
if (entry.Value is Product)
{
Product product = entry.Value as 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.Contains(key) == false)
{
// This key does not exist in cache
}
}
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
See Also
Connecting to Cache
Add Data to Cache
Update Data to Cache
Remove Data from Cache
Start Cache