Now insert the following code in the 'Main' of the project.
For Remove Method:
Cache _cache = NCache.initializeCache("myCache");
_cache.clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
customer.setCity("London");
customer.setContactNumber("+44-xxx-xxxx-xxxx");
customer.setOrderInProcess(true);
_cache.add("Customer:David:1001", customer);
// Removes object from Cache and returns back the object which was just deleted
Object removedObject = _cache.remove("Customer:David:1001");
Customer customerInformation = (Customer)removedObject;
System.out.println("Customer ID: " + customerInformation.customerID);
System.out.println("Name: " + customerInformation.name);
System.out.println("City: " + customerInformation.getCity());
System.out.println("Contact Number: " + customerInformation.getContactNumber());
System.out.println("Order placed: " + customerInformation.isOrderInProcess());
For Remove Item only if it is Latest:
There are cases where we want to remove the cache item from the Cache only if we have the latest version with us, i.e. not updated by any other instance of the client application. For this specific reason remove overload provided with CacheItemVersion can be used.
Cache _cache = NCache.initializeCache("myCache");
_cache.clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
customer.setCity("London");
customer.setContactNumber("+44-xxx-xxxx-xxxx");
customer.setOrderInProcess(true);
_cache.add("Customer:David:1001", customer);
// GetCacheItem Cache Item
CacheItem cItem = _cache.getCacheItem("Customer:David:1001");
// Your code ...
// Remove CacheItem only if you have the latest copy otherwise don't
Object removedObject = _cache.remove("Customer:David:1001", cItem.getVersion());
Customer customerInformation = (Customer)removedObject;
System.out.println("Customer ID: " + customerInformation.customerID);
System.out.println("Name: " + customerInformation.name);
System.out.println("City: " + customerInformation.getCity());
System.out.println("Contact Number: " + customerInformation.getContactNumber());
System.out.println("Order placed: " + customerInformation.isOrderInProcess());