Add/Update Data in Cache
After successful initialization of cache and gaining a valid cache handle, you can perform an “Add operation”. Add is a basic operation provided by NCache, and this can be used to add/update data to the cache using multiple API calls.
Key-value Cache Store
NCache uses key and a value to store objects. Every object is stored against a unique string based key associated with it. Every key has an atomic occurrence in the cache whether it is local or clustered. They are case-sensitive in nature and another key cannot be added with the same value.
Custom Objects
The value of the objects stored in the cache can range from being simple string types to complex objects. However, the custom object data must be serializable otherwise NCache will throw a serialization exception. You can also add data using the setValue
method of the CacheItem
class, which results in the data being saved internally as a CacheItem
.
Additionally you can use the NCache Dynamic Compact Serialization framework for custom objects. This framework provides cost effective serialization facilities for registered classes.
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 created.
- Make sure that the cache is running.
Adding Objects to Cache
In the following example an object of a custom class is created and added to the cache. Item has the properties provided below and added in the cache using the put
method.
try
{
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);
}
catch(Exception ex)
{
//Handle exception
}
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.
try
{
//precondition: Cache is already initialized and item exists
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);
}
catch(Exception ex)
{
// Handle Exception
}
Add CacheItem in Cache
CacheItem
is a custom class provided by NCache which can be used to add data to the cache. This class encapsulates data as its value property. CacheItem
lets user set additional values associated with an object as properties of this class.
try
{
cache = (Cache) jCache.unwrap(Cache.class);
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
CacheItem cacheItem = new CacheItem(product);
String key = "Product:" + product.getProductID();
// Add the cacheitem to the cache
cache.add(key, cacheItem);
}
catch(Exception ex)
{
// Handle Exception
}
Update CacheItems in Cache
In the following example, we update an existing object in the cache based on the key of the object using the custom class CacheItem
.
try
{
//precondition: Cache is already initialized and item exists
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
product.setUnitsInStock(5); // updated units
String key = "Product:" + product.getProductID();
CacheItem cacheItem = new CacheItem(product);
// Update CacheItem in Cache
cache.insert(key, cacheItem);
}
catch(Exception ex)
{
// Handle Exception
}
Add Bulk Items to the Cache
You can add a collection of items in the cache using addBulk
method. This method returns a HashMap of all the keys that failed to be added along with the exception, where NCache's JCache API provider remove method behaves as per JCache’s specifications.
try
{
Product product1 = new Product();
product1.ProductID = 1001;
product1.ProductName = "Chai";
product1.UnitsInStock = 4;
String key1 = "Product:" + product1.ProductID;
Product product2 = new Product();
product2.ProductID = 1002;
product2.ProductName = "Chang";
product2.UnitsInStock = 5;
String key2 = "Product:" + product2.ProductID;
HashMap map = new HashMap();
String[] keys = {key1, key2};
CacheItem[] items = new CacheItem[2];
items[0] = new CacheItem(product1);
items[1] = new CacheItem(product1);
for (int i = 0; i < 2; i++)
{
map.put(keys[i], items[i]);
}
jCache.putAll(map);
}
catch(Exception ex)
{
// Handle Exception
}
Update Bulk Data in Cache
You can update an existing collection of items with the help of the insertBulk
method or in Java you can also use NCache's JCache API provider.
try
{
Product product1 = new Product();
product1.ProductID = 1001;
product1.ProductName = "Chai";
product1.UnitsInStock = 5; //updated units
String key1 = "Product:" + product1.ProductID;
Product product2 = new Product();
product2.ProductID = 1002;
product2.ProductName = "Chang";
product2.UnitsInStock = 6; //updated units
String key2 = "Product:" + product2.ProductID;
HashMap map = new HashMap();
String[] keys = {key1, key2};
CacheItem[] items = new CacheItem[2];
items[0] = new CacheItem(product1);
items[1] = new CacheItem(product2);
for (int i = 0; i < 2; i++)
{
map.put(keys[i], items[i]);
}
jCache.putAll(map);
}
catch(Exception ex)
{
// Handle Exception
}
Add Items to Cache Asynchronously
When your application issues request for adding/updating data to the cache or removing from it with asynchronous API call, NCache uses a thread pool on the server side to facilitate these operations. Whereas in case of any callback registered with asynchronous operations, NCache triggers appropriate events only for interested clients upon operation completion.
You can add data to NCache asynchronously using the addAsync
method. The following example demonstrates adding an object to the cache asynchronously.
try
{
// Create a new Product
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
CacheItem cacheItem = new CacheItem(product);
String key = "Product:" + product.ProductID;
// Add Product to cache asynchronously
cache.addAsync(key, cacheItem, DSWriteOption.None, null);
}
catch(Exception ex)
{
// Handle Exception
}
Update Data in Cache Asynchronously
The insertAsync
method enables you to update previously added data to the cache in an asynchronous manner.
try
{
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
product.setCategory("4");// updated category
String key = "Product:" + product.getProductID();
CacheItem cacheItem = new CacheItem(product);
// Insert the item in the cache with new values
cache.insertAsync(key, cacheItem, DSWriteOption.None, null);
}
catch(Exception ex)
{
// Handle Exception
}
See Also
Initialize Cache
Fetch Items from Cache
Remove Operation in Cache
Hibernate Caching