Fetch 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 API, include the following namespace in your application: Alachisoft.NCache.Web.Caching.

Retrieve 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 objectwhich 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 isProduct)

{

product = (Product)result;

}

}

}

catch (OperationFailedException ex)

{

// handle exception

}

Retrieve a CacheItem

In this example, the basicGetCacheItemmethod is used to retrieve item “Product:1001”. This item has been added to the cache. This method returns CacheItemwhose 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 isProduct)

{

product = (Product)result.Value;

}

}

}

catch (OperationFailedException ex)

{

//handle exception

}

Retrieve Data with Cache Indexer

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";

Product product = null;

try

{

object result = cache[key];

if (result != null)

{

if (result isProduct)

{

product = (Product)result;

}

}

}

catch (OperationFailedException ex)

{

// handle exception

}

Check If an Item Exists in Cache

In order to verify if a key exists in the cache or not, theContainsmethod can be used. This method determines whether cache contains the specific key and returns true if key already exist in cache and false if not.