Step 5: Use JCS to quickly build a cache Environment

Source: Internet
Author: User

JCS is a subproject of the Turbine project of Jakarta. It is a compound buffer tool. It can buffer objects to memory and hard disk. The expiration time of the buffered object is set. JCS can also be used to build a buffer distributed architecture for high-performance applications. Objects that require frequent access and consume resources each time they are accessed can be temporarily stored in the buffer zone to improve service performance. JCS is a good buffer tool. The buffer tool significantly improves the performance of read Operations much more than write operations.


I. Understand the three core concepts of Cache

Elements: JCS is an object cache that can place some objects or "elements" and access them through keys, much like a hashtable. As you can imagine, JCS is a collection of hashtables that can be obtained by Name.

Regions: Each hashtables is called "region", and each region is independent of other regions configurations. For example, you can have a region called a city, which caches city objects that are regularly changed. You can define a region called a product and cache regularly changed product data. The regionelements of products that can be configured with ease of Change expire faster than the region of the city.

Auxiliaries: Auxiliaries is a plug-in option available for region. The core Auxiliaries are IndexedDisk Cache, TCPLateral Cache, and RemoteCache Server. For example, the disk cache allows you to swap cache objects to hard when the memory reaches the threshold.


Ii. Download JCS

You can download JCS from the JCS official website and view JCS related documents.


3. Obtain the Jar package on which JCS depends

JCS has two necessary Jar, namely jcs-1.3.jar and concurrent. jar, both of which can be downloaded from the official website. In addition, we 'd better download the jar packages supported by Log4j, because it is so convenient for us to print some logs.


4. Configure JCS

Create the cache. ccf configuration file in the src directory and Copy the following content to the file.

# DEFAULT CACHE REGION

Jcs. default =

Jcs. default. cacheattributes = org. apache. jcs. engine. CompositeCacheAttributes

Jcs. default. cacheattributes. MaxObjects = 1000

Jcs. default. cacheattributes. MemoryCacheName = org. apache. jcs. engine. memory. lru. LRUMemoryCache

Note that do not leave spaces after the equal sign "="; otherwise, the cache. ccf will not recognize it.


V. Start programming with JCS

5.1 create a CacheWrapper class and use it to add, retrieve, and remove objects.

package com.favccxx.favjcs;import org.apache.jcs.JCS;import org.apache.jcs.access.exception.CacheException;import org.apache.jcs.engine.CacheElement;public class CacheWrapper {              public JCS jcsCache = null;              public CacheWrapper(JCS cache){        this.jcsCache = cache;    }              public void put(String key , Object value){        try{            jcsCache.put(key, value);        }catch(CacheException e){            e.printStackTrace();        }    }              public Object get(String key){        CacheElement cacheElement = (CacheElement) jcsCache.getCacheElement(key);        if (null != cacheElement) {            Object object = cacheElement.val;            return object;        }        return null;    }          }

5.2 create a CacheFactory class and use the factory to manage cache objects to initialize cache and clear cache.

Package com. favccxx. favjcs; import java. util. hashMap; import java. util. map; import org. apache. jcs. JCS; import org. apache. jcs. access. exception. cacheException; import org. apache. log4j. logger; public class CacheFactory {private static Logger logger = Logger. getLogger (CacheFactory. class); private static Map <String, CacheWrapper> hashMapWrapper = new HashMap <String, CacheWrapper> ();/*** get a cache named cacheName Object; if not, return null * @ param cacheName * @ return */public static CacheWrapper getCacheWrapper (String cacheName) {logger. debug ("Get CacheWrapper, The cacheName is:" + cacheName); return hashMapWrapper. get (cacheName);}/*** clear all the caches */public static void revoke AchE () {Object [] cacheArray = hashMapWrapper. keySet (). toArray (); for (int I = 0, l = cacheArray. length; I <l; I ++) {try {String cacheName = cacheA Rray [I]. toString (); logger. debug ("The cache is below to clear, And the name is:" + cacheName); CacheWrapper cacheWrapper = hashMapWrapper. get (cacheName); cacheWrapper. jcsCache. clear ();} catch (CacheException e) {logger. debug ("Clear Cache Error! "); E. printStackTrace () ;}}/ *** gets a cache object named cacheName. If it does not exist, create a new cache object * @ param cacheName * @ return */private static CacheWrapper createCacheWrapper (String cacheName) {JCS cache = null; try {cache = JCS. getInstance (cacheName); return new CacheWrapper (cache);} catch (CacheException e) {return null ;}} /*** create a cache object * @ param cacheName */private static void createHashMapWrapper (String cacheName) {hashMapWrapper. put (cacheName, createCacheWrapper (cacheName);}/*** initialize cache object */public static void initCache () {logger. debug ("By Start initCache Method, We create all the Cache Object"); createHashMapWrapper ("coolBoyCache"); // createHashMapWrapper ("beautifulGirl ");}}

5.3 create a test class TestCache and test the cache object just now.

package com.favccxx.favjcs.web;import com.favccxx.favjcs.CacheFactory;public class TestCache {    /**     * @param args     */    public static void main(String[] args) {        CacheFactory.initCache();        CacheFactory.getCacheWrapper("coolBoy");    }}


This article from the "dust wind with the shadows of the Sky" blog, please be sure to keep this source http://genuinecx.blog.51cto.com/2890523/1204907

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.