Tuesday, 25 June 2013

JCS implementation in JAVA



Java Caching System (JCS)

It’s a distributed caching system written in java. It is used to speed up applications by providing a way to manage cached data of various dynamic environments. JCS is most helpful for the applications where read operations are highly preferable than update operations.


It provides multiple additional features like below:
  • Memory management
  • Thread pool controls
  • Minimal dependencies
  • Data expiration (idle time and max life)
  • Extensible framework
  • Fully configurable runtime parameters
  • Region data separation and configuration
  • Remote synchronization
  • Remote store recovery
  • Element event handling
  • Custom event logging hooks
  • Custom event queue injection
  • Custom object serializer injection
  • Key pattern matching retrieval



Feature Details:-

  • JCS: - It’s a cache which supports caching data in memory, or a disk on a remote server using RMI. It is very much suitable for caching data on the Data Access layer.
  • It doesn't provide any provision to support caching of HttpResponse and Page Fragment caching on the presentation layer.
  • It helps in supporting for distributed cache. All updates and invalidations to the local cache are broadcast to all the caches involved in the cluster. Hence, it can be inferred that it is very much suitable for those applications which is having frequent reads and infrequent updates process.
  • Its cache area can be in indexed disk space, remote cache, memory and lateral cache. JCS is having the facility where a combination of caches can also be configured. If the memory area is full, objects are bounced to disk.
  • In JCS, the data in the disk is indexed to facilitate easy retrieval from disk. The facility for handling a remote cache is more suitable when we have multiple web server JVMs running on the same node.
  • A property file named config.ccf is needed to set JCS configurations.
  • It helps for accessing its cache from a Java class using JCS API.

Question: - What is Page Fragment caching?

Answer: - Page fragment caching provides a facility to wrap a part of logic in a cache block used in the page and served out of the cache store when the next request comes in.


Question: - How to implement JCS in java?
Answer:-  

Example of JCS implementation in Java.


System Requirements:-

          Eclipse Editor or any other.
         JDK 1.5 or higher(I am using jdk 1.7.0_03)
         JCS jars.


Required Jars are:-

commons-logging.jar
commons-lang-2.4.jar
concurrent.jar
jcs-1.3.jar


Steps for creating Eclipse java project for implementing Java Caching System:-

  • Create a java project in eclipse.
  • Create a package in the src folder with the name as com.gaurav.apachejcs.impl.
  • Add the required jars in the build path of the project.
  • Create the Product.java and ProductManager.java files in this package and place the corresponding below available code in those files.
  • Create a cache.ccf file and place the below code in that file. This file is used for the JCS configurations. This file needs to be placed in the src folder.
  • Execute the ProductManager.java by selecting the option Run as Java Application.

Product.java

package com.gaurav.apachejcs.impl;

/**
 * @author Gaurav
 *
 */
public class Product implements java.io.Serializable {
      /**
       *
       */
      private static final long serialVersionUID = -5372772868069600498L;
      private String productId;
      private String productName;
      private String productMaker;

      public Product(){

      }
      public Product(String prodId, String prodName, String prodMaker){
            this.productId = prodId;
            this.productName = prodName;
            this.productMaker = prodMaker;
      }
      /**
       * @return the productId
       */
      public String getProductId() {
            return productId;
      }
      /**
       * @param productId the productId to set
       */
      public void setProductId(String productId) {
            this.productId = productId;
      }
      /**
       * @return the productName
       */
      public String getProductName() {
            return productName;
      }
      /**
       * @param productName the productName to set
       */
      public void setProductName(String productName) {
            this.productName = productName;
      }

      /**
       * @return the productMaker
       */
      public String getProductMaker() {
            return productMaker;
      }
      /**
       * @param productMaker the productMaker to set
       */
      public void setProductMaker(String productMaker) {
            this.productMaker = productMaker;
      }

      @Override
      public String toString() {
            return productName + " made by " + productMaker + " and Model No is : " + productId;
      }

}


ProductManager.java


package com.gaurav.apachejcs.impl;

import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;



public class ProductManager {
      private JCS jcsCache;

      public ProductManager() {
            try {
                  // Loading the cache using the configuration file
                  jcsCache = JCS.getInstance("productDetailsCache");

                  // Initializing the cache by putting two product data into cache.
                  jcsCache.put("KDL-32EX650", new Product("KDL-32EX650",
                              "BRAVIA Full HD with Edge LED", "SONY"));
                  jcsCache.put("72LM9500", new Product("72LM9500",
                              "Full HD LED 3D Smart TV", "LG"));

            } catch (CacheException e) {
                  e.printStackTrace();
            }
      }

      public void addProductInCache(Product product) {
            try {
                  jcsCache.put(product.getProductId(), product);
            } catch (CacheException e) {
                  e.printStackTrace();
            }
      }

      public Product getProductById(String productId) {
            return (Product) jcsCache.get(productId);
      }

      public void removeProductFromCache(String productId) {
            try {
                  jcsCache.remove(productId);
            } catch (CacheException e) {
                  e.printStackTrace();
            }
      }

      public static void main(String[] args) {
            // Creating the ProductManager instance
            ProductManager productManager = new ProductManager();

            // Adding one more product data in the cache.
            productManager.addProductInCache(new Product("UA85S9AR",
                        "Smart TV 2.0", "Samsung"));

            // Getting all the products details which is added in cache

            Product product = productManager.getProductById("KDL-32EX650");
            System.out.println("The First Product retrieved from cache is :- " + product);

            product = productManager.getProductById("72LM9500");
            System.out.println("The Second Product retrieved from cache is :- " + product);

            product = productManager.getProductById("UA85S9AR");
            System.out.println("The Third Product retrieved from cache is :- " + product);


            // Removing a product from the productManager
            productManager.removeProductFromCache("KDL-32EX650");

            // Cross checking that the removed product is still available or not.
            System.out.println("\n**********************************************************************************************");
            System.out
                        .println("Again trying to retrieve the First product from the cache after removing the First product:- "
                                    + productManager.getProductById("KDL-32EX650"));
            System.out.println("**********************************************************************************************\n");

            System.out
            .println("Again trying to retrieve the Second product from the cache after removing the First product:- "
                        + productManager.getProductById("72LM9500"));

            System.out
            .println("Again trying to retrieve the Third product from the cache after removing the First product:- "
                        + productManager.getProductById("UA85S9AR"));

      }
}

Note: - We have wrapped the JCS get, put and remove methods in the ProductManager class
  • put (): puts an object in the cache, of the form (key, value). In this example, the product’s ID is the key and the value is the Product.
  • get(): returns the object with the specified primary key
  • remove(): removes the object with the specified primary key

cache.ccf

# DEFINING CACHE REGIONS FOR PRODUCTDETAILSCACHE

# -------The most basic configuration would be a pure memory cache where every region takes the default values.---------

jcs.region.productDetailsCache=DC
jcs.region.productDetailsCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
jcs.region.productDetailsCache.cacheattributes.MaxObjects=1000
jcs.region.productDetailsCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache

#------ IF WE WANT TO ADD MEMORY SHRINKING THEN WE CAN ADD THESE LINES ---------------

jcs.region.productDetailsCache.cacheattributes.ShrinkerIntervalSeconds=60
jcs.region.productDetailsCache.cacheattributes.MaxSpoolPerRun=500
jcs.region.productDetailsCache.elementattributes=org.apache.jcs.engine.ElementAttributes
jcs.region.productDetailsCache.elementattributes.IsEternal=false
jcs.region.productDetailsCache.cacheattributes.UseMemoryShrinker=true
jcs.region.productDetailsCache.cacheattributes.MaxMemoryIdleTimeSeconds=3600

#--------- FOR MORE CONFIGURATION DETAILS VISIT:- http://commons.apache.org/proper/commons-jcs/BasicJCSConfiguration.html ------------

Result:-

Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheManager configure
INFO: Creating cache manager from config file: /cache.ccf
Jun 26, 2013 6:51:10 AM org.apache.jcs.utils.threadpool.ThreadPoolManager loadConfig
INFO: thread_pool.default PoolConfiguration = useBoundary = [true] boundarySize = [2000] maximumPoolSize = [150] minimumPoolSize = [4] keepAliveTime = [300000] whenBlockedPolicy = [RUN] startUpSize = [4]
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator setDefaultAuxValues
INFO: Setting default auxiliaries to null
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator parseCompositeCacheAttributes
INFO: No special CompositeCacheAttributes class defined for key [jcs.default.cacheattributes], using default class.
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator setDefaultCompositeCacheAttributes
INFO: setting defaultCompositeCacheAttributes to [ useLateral = true, useRemote = true, useDisk = true, maxObjs = 100, maxSpoolPerRun = -1, diskUsagePattern = 0 ]
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator parseElementAttributes
INFO: No special ElementAttribute class defined for key [jcs.default.elementattributes], using default class.
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator setDefaultElementAttributes
INFO: setting defaultElementAttributes to [ IS_LATERAL = true, IS_SPOOL = true, IS_REMOTE = true, IS_ETERNAL = true, MaxLifeSeconds = -1, IdleTime = -1, CreateTime = 1372209670187, LastAccessTime = 1372209670187, getTimeToLiveSeconds() = -1, createTime = 1372209670187 ]
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.memory.lru.LRUMemoryCache initialize
INFO: initialized LRUMemoryCache for productDetailsCache
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCache <init>
INFO: Constructed cache with name [productDetailsCache] and cache attributes [ useLateral = true, useRemote = true, useDisk = true, maxObjs = 1000, maxSpoolPerRun = 500, diskUsagePattern = 0 ]
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator parseAuxiliary
SEVERE: Could not instantiate auxFactory named "DC".
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator parseRegions
INFO: Parsed regions [productDetailsCache]
Jun 26, 2013 6:51:10 AM org.apache.jcs.engine.control.CompositeCacheConfigurator doConfigure
INFO: Finished configuration in 219 ms.
The First Product retrieved from cache is :- BRAVIA Full HD with Edge LED made by SONY and Model No is : KDL-32EX650
The Second Product retrieved from cache is :- Full HD LED 3D Smart TV made by LG and Model No is : 72LM9500
The Third Product retrieved from cache is :- Smart TV 2.0 made by Samsung and Model No is : UA85S9AR

**********************************************************************************************
Again trying to retrieve the First product from the cache after removing the First product:- null
**********************************************************************************************

Again trying to retrieve the Second product from the cache after removing the First product:- Full HD LED 3D Smart TV made by LG and Model No is : 72LM9500
Again trying to retrieve the Third product from the cache after removing the First product:- Smart TV 2.0 made by Samsung and Model No is : UA85S9AR


reference taken from http://commons.apache.org

2 comments:

  1. Hi in jcs ...I gave once region in cache.ccf...I kept one value in cache in one class..I want to use the same key valye in some other class..how can i use it?

    ReplyDelete
    Replies
    1. here some other class means some other package

      Delete