JCache: Initialize Cache
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 JCache CRUD Operations
- For using JCache with NCache Professional, replace the
ncache-client
withncache-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 Serialization format.
- Ensure that the cache is running.
Initialize Cache
To obtain a cache instance in Java, use the getCache method from 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 advanced caching features including Locking, Groups, Pub/Sub Messaging, Tags, and SQL-like querying capabilities, which can be crucial for complex, distributed, and high-load scenarios. To access all of NCache's features via JCache, you can utilize the unwrap
method provided by NCache. This method allows you to obtain actual instance of NCache, which can then be used to access and utilize all of NCache's capabilities.
This example creates an instance of the JCache caching provider, which then retrieves the JCache Manager. From the manager, it unwraps the NCache instance and obtains a cache by 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");
// Unwrapping NCache's cache instance from JCache's cache instance.
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 previously configured and running.
//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 getting a cache handle, you can perform a 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("1001", "Chai");
String key1 = "Product:" + product1.getProductID();
Product product2 = new Product("1002", "Coffee");
String key2 = "Product:" + product2.getProductID();
// Data to add in cache
HashMap dataMap = new HashMap();
dataMap.put(key1, product1);
dataMap.put(key2, product2);
// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Add/Update all keys in the cache
jCache.putAll(dataMap);
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 already exists in 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.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Key to get
String key = "Product:1001";
//Get specified item
Product product = (Product) jCache.get(key);
if (product != null) {
// business logic
}
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.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
HashSet keysToGet = new HashSet();
keysToGet.add("Product:1001");
keysToGet.add("Product:1002");
Map productsMap = jCache.getAll(keysToGet);
if (!productsMap.isEmpty())
{
for (Iterator iter = productsMap.values().iterator(); iter.hasNext();)
{
Product product = (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 mapping associated with a specified key from the cache, if it 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.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Key to remove.
String key = "Product:1001";
// False is returned if key does not exist in cache.
boolean result = jCache.remove(key);
if (result != true) {
//Deleted.
}
else {
//Failed.
}
Remove Bulk Data
The following code snippet removes the items in bulk from the cache through the removeAll
method. The code gets an instance of the JCache Manager, obtains the required cache from the manager, and defines keys against which the data is to be removed.
// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Keys to remove
HashSet set = new HashSet();
set.add("Product:1001");
set.add("Product:1002");
// Removing all keys
jCache.removeAll(set);
Clear Cache
To clear the cache completely (in the background), you need to call the clear
method.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Clear the Cache.
jCache.clear();
See Also
Event Notifications in Cache
Hibernate Caching
NCache Java Session Module