CRUD Operations with JCache
After successfully plugging NCache into your JCache application, a cache instance is required to perform cache operations. Java applications can also interact with NCache using the JCache API provider packaged as a part of NCache. The JCache API provider provides a convenient method to initialize the cache instance.
Prerequisites
- For using JCache with NCache Professional, replace the ncache-client with ncache-professional-client in your pom.xml.
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Include the following packages and their libraries in your application from the NCache install directory.
import javax.cache.CacheManager
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
- Make sure that the data is serialized or registered with the NCache Compact Serialization format.
- Ensure that the cache is running.
Initialize Cache
The most convenient method of getting a cache instance in Java is to use the getCache
method of the JCache CacheManager provided by NCache. You can get an instance of a previously configured cache by using its name (unique identifier) as an argument to the getCache
method.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
Obtaining NCache API's Cache Instance
NCache's API provides comparatively more flexible and convenient caching features than JCache's API. To access all of NCache's features via JCache, you can utilize the unwrap
method provided by NCache. This method allows you to obtain the actual instance, which can then be used to access and utilize all of NCache's capabilities.
This example creates an instance of JCache's caching provider to get JCacheManager's instance by NCache and gets a cache from manager through its name.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache.
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
com.alachisoft.ncache.client.Cache cache = (com.alachisoft.ncache.client.Cache) jCache.unwrap(com.alachisoft.ncache.client.Cache.class);
Initialize Multiple Caches in a Single Application
To initialize multiple caches in a single application, it is necessary for caches to be configured previously and also be in a running state.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache demoCache = manager.getCache("demoCache");
javax.cache.Cache productCache = manager.getCache("productCache");
Add/Update Data in Cache
After successful initialization and gaining a cache handle, you can perform put
operation. It is a basic operation provided by JCache, and this can be used to add/update data to the cache using multiple API calls.
Adding Objects to Cache
In the following example, an object of a custom class is created and added to the cache. This item has all the properties provided in the code below and is added to the cache using the put
method.
// Ensure that Cache is already initialized and the item exists
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
String key = "Product:" + product.getProductID();
// Add data in cache with the values
jCache.put(key, product);
Update Data in Cache
In the following example, an object of a custom class is updated in the cache. The replace
method overwrites the already existing value of the object.
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
product.setUnitsInStock(5); // updated units
String key = "Product:" + product.getProductID();
// Replace the item in the cache with updated item
jCache.replace(key, product);
Add and Update Bulk Items in Cache
You can add and update an entire collection of items in the cache using the putAll
method. This method returns a HashMap of all the keys that were not added along with the exception.
Product product1 = new Product();
product1.setProductID("1001");
product1.setProductName("Chai");
String key1 = "Product:" + product1.getProductID();
Product product2 = new Product();
product1.setProductID("1002");
product1.setProductName("Coffee");
String key2 = "Product:" + product2.getProductID();
Product[] products = new Product[2];
products[0] = product1;
products[1] = product2;
HashMap map = new HashMap();
String[] keys = {key1, key2};
for (int i = 0; i < 2; i++)
{
map.put(keys[i], items[i]);
}
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
jCache.putAll(map);
Retrieve from Cache
JCache uses get
method to retrieve a specific entry from the cache through key.
Retrieve a Single Item from the Cache
In the following example, we use the default get
method to retrieve a pre-existing object "Product:1001". This item has been previously added to the cache. The get
method returns an object which needs to be cast accordingly. If a matching key does not exist in the cache, a null
value is returned.
//Ensure that data already exists in the cache
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;
}
}
Retrieve Bulk Data from Cache
For fetching a collection from the cache, use the getAll
method. This method returns a collection of items as a HashMap.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
HashSet set = new HashSet();
set.add("Product:1001");
set.add("Product:1002");
Map items = jCache.getAll(set);
if (!items.isEmpty())
{
for (Iterator iter = items.values().iterator(); iter.hasNext();)
{
Product product5 = (Product) iter.next();
//utilize product object accordingly
}
}
Remove Data from Cache
JCache provides remove
method to remove the mapping for an existing key from the cache.
Using Remove Method
The remove method in the JCache API removes a mapping associated with a specified key from the cache, if that exists. The method returns true if the cache contains the key and the removal was successful, or false if there is no mapping for the key.The following example removes the key mappings for Product class.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
Cache cache = (Cache) jCache.unwrap(Cache.class);
String key = "Product:1001";
Product product = null;
// False is returned if key does not exist in cache
boolean result = cache.remove(key, Product.class);
if (result != true)
{
//Deleted.
}
else
{
//Failed.
}
Clear Cache
To clear the cache completely in the background, you need to call the jCache.clear
method.
jCache.clear();
See Also
Event Notifications in Cache
Hibernate Caching
NCache Java Session Module