Items can be retrieved from the cache by using Get method. Overloaded methods are also explained below:
Using Get Method:
Here is how you can retrieve items from the cache.
//returns null if item not found
Object myObject = _cache.get("Customer:Alex:1002");
if(myObject == null)
{
//item not found
}
To get latest Cache value of cache Item:
-
Include the following import statements in your project:
import com.alachisoft.ncache.web.caching.*;
-
Create a new Class named 'Customer' in your already created Test Application.
-
Insert the following code in the 'Customer' class.
import java.io.Serializable;
public class Customer implements Serializable
{
.....
}
-
Now insert the following code in 'Main' of the project.
Cache _cache = NCache.initializeCache("myCache");
_cache.clear();
Customer customer = new Customer();
customer.name = "David";
customer.Id = 1001;
// Add Item to Cache
_cache.add("Customer:David:1001", customer);
// Get the latest value with respect to key "Customer:David:1001"
CacheItem cItem = _cache.getCacheItem("Customer:David:1001");
if (cItem != null) // check if Item does exist
{
// do some operations
// ...
// Update the Cache Item, to change the item version, to perform the test
_cache.insert("Customer:David:1001", customer);
CacheItem cItem1 = _cache.getCacheItem("Customer:David:1001");
Customer customer1 = (Customer) cItem1.getValue();
System.out.println("Customer ID: " + customer1.Id);
System.out.println("Name: " + customer1.name);
}
5. Start the Local Cache 'myCache'.
6. Run the project.
See Also