Fetching Data from Cache
Primarily a cache is only considered as effective as its ability to retrieve data. NCache utilizes the key-value architecture of its store to maximize the ways of data retrieval. Get method is the primary API provided to serve previously cached data; however basic indexer approach can also be used. Both of these methods are explained below.
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Web.Caching.
Retrieving Data Using Get() Method
In this example, the basic Get method is used to retrieve item Product:1001
.
This item has previously been added to the cache. Get method returns general
object which needs to be cast accordingly. If a key does not exist in cache null
value is returned.
string key = "Product:1001";
Product product = null;
try{
//null is returned if key does not exist in the cache.
object result = cache.Get(key);
if (result != null)
{
if (result is Product)
{
product = (Product)result;
}
}
}
catch (OperationFailedException ex){
// handle exception
}
Retrieve a CacheItem from Cache
In this example, the basic
GetCacheItem
method is used to retrieve item Product:1001
. This item has been added to the
cache. This method returns CacheItem
whose value property encapsulates the data;
the Object value need to be cast accordingly.
string key = "Product:1001";
Product product = null;
try{
CacheItem result = cache.GetCacheItem(key);
if (result != null)
{
if (result.Value is Product){
product = (Product)result.Value;
}
}
}
catch (OperationFailedException ex){
//handle exception
}
Checking if an Item Exists in Cache
NCache being a key-value paired structure lets the user perform operations like
any other indexed based data structure. In this example a cache handle is used
to directly access cached values using square brackets ”[]
”.
string key = "Product:1001";try
{
if (cache.Contains(key))
{
//do something
}
else
{
//do something
}
}
catch (OperationFailedException ex){
//handle exception
}