Retrieve from Cache
NCache utilizes the key-value architecture for retrieval of data residing in cache. The Get
method is the primary method in the API to retrieve data.
Pre-Requisites
- Add the following Maven dependencies in your
pom.xml
file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>5.2.0</version>
</dependency>
- Import the following packages in your application:
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
- Make sure that the data is serailized or registered with NCache Compact Serialization format.
- Make sure that the cache is running.
Retrieve a Single Item from Cache
In the following example we use the default get method to retrieve an object identified by “Product:1001”. This item has been previously added to the cache. The Get
method returns a general object which needs to be cast accordingly. If the matching key does not exist in the cache, null
value is returned by get.
try
{
String key = "Product:1001";
Product product = null;
//null is returned if key does not exist in the cache.
Object result;
result = jCache.get(key);
if (result != null)
{
if (result instanceof Product)
{
product = (Product) result;
}
}
}
catch(Exception ex)
{
// Handle exception
}
Retrieve a CacheItem from Cache
In the following example we use the GetCacheItem
method to retrieve an object identified by “Product:1001”. This item has previously been added to the cache. This method returns a CacheItem
object whose value property encapsulates the data, which needs to be cast appropriately for further use in the application.
try
{
String key = "Product:1001";
Product product = null;
CacheItem retrievedData = cache.getCacheItem(key);
if (retrievedData != null)
{
if (retrievedData.getValue() instanceof Product)
{
product = (Product) retrievedData.getValue();
}
}
}
catch(Exception ex)
{
// Handle Exception
}
Retrieve Bulk Data from Cache
For fetching a collection from cache, use the getBulk method. This method returns the collection of items in a HashMap; however NCache’s JCache API provider can also be used for the same purpose.
try
{
//pre-condition: data already exists in the cache
HashMap map = new HashMap();
Map items = jCache.getAll(map.keySet());
if (!items.isEmpty())
{
for (Iterator iter = items.values().iterator();iter.hasNext();)
{
Product product = (Product) iter.next();
//utilize product object accordingly
}
}
}
catch(Exception ex)
{
// Handle Exception
}
See Also
Initialize Cache
Add/Update in Cache
Remove Operation in Cache
Hibernate Caching
NCache Java Session Module