Cookie Consent by Free Privacy Policy Generator JCache Provider for NCache

JCache Provider for NCache

JCache is a Java based API used for in memory caching of Java objects. This also includes creation of objects, invalidation, spooling, shared access and consistency across Java Virtual Machines (JVMs).

NCache is a very powerful and versatile distributed caching solution that comes with a vast set of features and tools. NCache provides an implementation of JCache (JSR 107) specification. Using this, you can reap the benefits of the vast number of features and tools provided by NCache.

Initialize Cache

The creation of a JCache instance is required in order for you to perform any operations on the cache. In Java, the getCache () method is considered to be one of the most convenient methods of getting JCache instance. The following code example demonstrates how you can initialize a cache using this method.

/*Create an instance of JCache's caching provider to get JCacheManager's instance */
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();

/*Get a cache from manager via its string name.*/
javax.cache.Cache jCache = manager.getCache("myreplicatedcache");

Basic Cache Operations

Once the cache has been initialized successfully and you have acquired a cache handle, you can perform many operations on the cache like adding, fetching, updating, and deleting data from the cache.

The following code example demonstrates how you can use the cache instance (which you created in the code example above) to perform basic operations on the cache.

/*Adding data to the cache*/
Product product = fetchProductFromDB();
String key = "Product:" + product.getProductID();       
jCache.put(key, product);

/*Update data in the cache*/
product.setUnitsInStock(newValue); // updated units
jCache.replace(key, product);
	
/*Get data from the cache*/
Object item = jCache.get(key);
	
/*Remove data from the cache*/
Boolean result = jCache.remove(key);

Data Expiration in Cache

Another feature of JCache is Data Expiration where cache data is expired on the basis of time. JCache supports two main types of expirations namely Absolute Expiration and Sliding Expiration. In Absolute expiration, data within the cache is expired after a fixed time interval. In Sliding expiration, data within the cache is expired after a time interval but, this time interval is reset every time this data is accessed.

Items can be added and updated in the cache with Absolute and Sliding expirations defined. In the following code example data is added into the cache with Absolute expiration defined.

CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager manager = cachingProvider.getCacheManager();
    Customer customer = new Customer();
    customer.setAge(22);
    String key = "Customer:" + customer.getCustomerID();

    //configure the expiration duration
    CompleteConfiguration<Object, Object> cacheConfig = new MutableConfiguration().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));

    //create cache with customized configuration settings
    javax.cache.Cache jCache = manager.createCache("mypartitionedcache", cacheConfig);

    //add item to cache which will expire after 1 minute
    jCache.put(key, customer);

Event Notifications in Cache

Cache Level Notifications are general events that are triggered when certain registered events occur. In order to get event(s) notifications from JCache, you need to implement the relevant event related interfaces.

In the example below, it is assumed that you have implemented the event-filter factory.

// class that implements the event-listener factory
public class MyCacheEntryListener<K, V>
   implements CacheEntryCreatedListener<K, V>, Serializable
   {...
           for (CacheEntryEvent<? extends K,? extends V> event: events)
            {
            System.out.println("Received a " + event);
            }
      ...
    }
    ...
//configuring
MyCacheEntryListener<String,String> m_listener = new MyCacheEntryListener<String,String>();

MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();

config.setTypes(String.class, String.class).addCacheEntryListenerConfiguration(
                    new MutableCacheEntryListenerConfiguration<String, String>
                            (FactoryBuilder.factoryOf(m_listener),FactoryBuilder.factoryOf(
                                    new MyCacheEntryEventFilter<String, String>()),true,true));

Cache<String, String> jCache = cacheManager.createCache("myreplicatedcache", config);

Using NCache API

The API provided by NCache gives you more robust features and functions as compared to the API provided by JCache. Some of the features which NCache provides but JCache does not are as follows:

In order to use all of these features provided by the NCache API you need to have an instance of its cache.

The following code example demonstrates how you can use a JCache API to get a cache instance of NCache by using the unwrap method. This Instance is then used to add data into the cache with tags (feature of NCache) enabled. These tags can be used instead of keys to retrieve data from the cache later on.

... 
com.alachisoft.ncache.client.Cache cache = null;
cache = (com.alachisoft.ncache.client.Cache) jCache.unwrap(com.alachisoft.ncache.client.Cache.class);
Customer customer = fetchCustomer();
String customerKey = “Customer” + customer.getCustomerID();

// Specify Tags
List<Tag> tags = List.of(new Tag("East Coast Customers"));
CacheItem cacheItem = new CacheItem(customer);
cacheItem.setTags(tags);
cache.add(customerKey, cacheItem);

What to Do Next?

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.