Java Cache Framework

Source: Internet
Author: User
Tags delete cache jboss

CacheFrame stew All kinds of open source cache solutions
  • Jbosscache/treecache
    Jbosscache is a replicated transaction cache that allows you to cache enterprise application data to better improve performance. Cached data is automatically copied, allowing you to easily perform cluster work between JBoss servers. Jbosscache can run an Mbean service through JBoss application service or another Java EE container, and of course it can run independently. The Jbosscache consists of two modules: Treecache and TREECACHEAOP. Treecache--is a tree-structured transactional cache of replication. TREECACHEAOP--is an "object-oriented" cache that uses AOP to dynamically manage Pojo

  • Oscache
    Designed by Opensymphony, the Oscache tag library is a groundbreaking JSP custom tagging application that provides the ability to implement fast memory buffering within existing JSP pages. Oscache is a broad-based, high-performance, Oscache cache framework that can be used in a common caching solution for any Java application. Oscache has the following features: Caching any object, you can cache part of the JSP page or HTTP request without restriction, any Java object can be cached. Having a comprehensive Api--oscache API gives you a comprehensive program to control all the Oscache features.

    1. Persistent caching-caches can write to the hard disk at will, so it allows expensive creation (expensive-to-create) of data to keep the cache, even allowing the app to restart.
    2. Support cluster--the cluster cache data can be configured by a single parameter without the need to modify the code.
    3. Expiration of cached records-you can have maximum control over expiration of cached objects, including pluggable refresh policies (if default performance is not required).
  • Jcache
    Jcache is an upcoming standard specification (JSR 107) that illustrates a way to temporarily cache Java objects in memory, including object creation, shared access, spooling (spooling), invalidation , consistency of each JVM, and so on. It can be used to cache the most frequently read data in a JSP, such as a product catalog and a price list. With Jcache, the response time of most queries can be accelerated by having cached data (internal tests indicate a response time of about 15 times times faster).

  • Ehcache
    Ehcache is derived from hibernate and used in hibernate as a solution for data caching. (Details will be introduced later)

  • Java Caching System
    JCS is a subproject of the Jakarta Project turbine. It is a composite buffer tool. You can buffer objects to memory, hard disks. Has buffer object time expiration setting. You can also build a distributed, buffered architecture with JCS for high-performance applications. For some objects that require frequent access and are very resource-intensive each time they are accessed, they can be temporarily stored in a buffer, which can improve the performance of the service. And JCS is a good buffer tool. The buffer tool is significantly more useful for read operations than write operations.

  • Swarmcache
    Swarmcache is a simple and powerful distributed caching mechanism. It uses IP multicast to effectively communicate between cached instances. It is an ideal choice to quickly improve the performance of clustered Web applications.

  • Shiftone
    Shiftone Object Cache This Java library provides basic objects caching capabilities. The implemented strategy is first-in, in-out (FIFO), Recently Used (LRU), least frequently Used (LFU). All policies maximize the size of the element and maximize its lifetime .

  • Whirlycache
    Whirlycache is a fast, configurable cache of objects that exist in memory. It can speed up the site or application by caching objects, or it must be established by querying the database or other expensive handlers.

  • Jofti Jofti
    Objects in the cache layer (supporting Ehcache,jbosscache and Oscache) or objects in a storage structure that supports the map interface can be indexed and searched. The framework also provides an easy-to-use query function for search by providing transparent functionality for object additions and deletions in the index.

  • Cache4j
    Cache 4j is a simple API with a fast implementation of Java object caching. Its features include: Caching in memory, designed for multithreaded environments, two implementations: synchronization and blocking, multiple cache purge policies: LFU, LRU, FIFO, use of strong references (strong reference) and soft references (soft reference) to store objects.

  • Open Terracotta
    A JVM-level open-source cluster framework that provides: HTTP session replication, distributed caching, Pojo clustering, cross-cluster JVM for distributed application Orchestration (in the form of code injection, so you don't need to modify anything).

  • Sccache
    Shop. The object cache system used by COM. Sccache is a in-process cache with level two, shared caches. It stores the cached object on disk. Supports association key, any size key and any size data. Ability to automate garbage collection.

  • Shoal
    Shoal is a Java-extensible dynamic Cluster framework that provides infrastructure support for building fault-tolerant, reliable, and usable Java applications. This framework can also be integrated into any Java product that does not want to be bound to a specific communication protocol but requires clustering and distributed system support. Shoal is the cluster engine for GlassFish and Jonas application servers.

  • Simple-spring-memcached
    Simple-spring-memcached, which encapsulates the call to Memcached, makes Memcached client development unusually simple.

  • Directmemory
    Directmemory is an implementation of the out-of-heap (off-heap) cache bigmemory. It can serialize large-volume Java objects in memory without affecting the performance of JVM garbage collection.

  • Multicache4j
    MULTICACHE4J is used to integrate various cache components for Java:

    1. Easy integration of various remote caches
    2. Memcached (Support component spymemcached)
    3. Memcachedb (Support component spymemcached)
    4. Ttserver (Support component spymemcached, ttserverclient)
    5. Redis (Support component Jedis)
    6. Easy integration of various local caches
    7. Ehcache
    8. Manage client connection objects based on object pooling technology, network disconnection can automatically reconnect
    9. Hash mapping based on pattern mapping
    10. Hybrid cache support for remote cache and local cache
    11. Support for separate use of the local cache
CacheCharacteristics

Whatever the solution, it has the following basic features.
1. Time History
The time the data entered the Cache .
2. Timeout Expiration time
How long does the data inside the Cache expire?
3. Eviction policy Cleanup Policies
After the Cache is full, which data should be purged according to what strategy.
For example, the least frequently accessed data is the data that has not been accessed for the longest time.
4. Hit Rate
The ratio at which the Cache data is selected
5. Tiered Cache
Some caches have a concept of grading. For example, almost all caches support the concept of region partitioning. You can designate a class of data to be stored in a specific region. The JBoss Cache can support more levels.
6. Distributed Cache
caches that are distributed on different computers
7. Lock, transaction, data synchronization
Some caches provide a perfect lock, transaction support.

The above features, most caches have the corresponding API support. These APIs are intuitive and simple.

Ehcahe

Ehcache from hibernate, gradually covering all the functions of the cache , is currently the best development of a project, with fast, simple, low consumption, strong extensibility, support objects or serialization cache, support cache or element invalidation , provides LRU, LFU, and FIFO cache policies, supports memory caching and hard disk caching, and distributed caching mechanisms. Where the Cache is stored as memory or disk

Basic usage
CacheManager CacheManager = cachemanager.create ()///CacheManager = Cachemanager.getinstance ();//or CacheManager = Cachemanager.create ("/config/ehcache.xml");//or CacheManager = Cachemanager.create ("http://localhost:8080/test/ Ehcache.xml "); CacheManager = Cachemanager.newinstance ("/config/ehcache.xml ");//... gets a ehcache configuration fileCacheCacheSample = Cachemanager.getcache ("sample");//Get page cache BlockingcacheCache= New Blockingcache (Cachemanager.getehcache ("Simplepagecachingfilter"));//Add data to the cache element element = new Element ("key "," Val "); Sample.put (element);//Get the object in the cache, note the addition to theCacheThe object to serialize implements the Serializable interface element result = Sample.get ("key");//delete cache Sample.remove ("key"); Sample.removeall ();// Gets the cache configuration name for the cache manager for (String CacheName:cacheManager.getCacheNames ()) {System.out.println (cachename);} Gets all the cached objects for (object key:Cache. Getkeys ()) {System.out.println (key);} Get the number of objects in the cacheCache. GetSize ();//Gets the size of the cache object that occupies memoryCache. Getmemorystoresize ();//Gets the cache read hit countCache. Getstatistics (). Getcachehits ();//Gets the number of missed cache readsCache. Getstatistics (). getcachemisses ();
Using Ehcahe page cache and object caching in spring

1. Download the jar Package

    • Ehcache object, data cache: Ehcache-core-2.5.2.jar
    • Web Page cache: Ehcache-web-2.0.4.jar

2. Bring the jar package into Lib

3. Introduction of configuration Files

    • Ehcache.xml
    • Ehcache.xsd
Page Caching

The page cache uses the filter filter to filter the requested URL, if the URL appears in the cache. The page data is then fetched from the cache object and returned with gzip compression. Its speed is 3-5 times the speed without compressing the cache, the efficiency is quite high! Where the page cache filter has cachingfilter, generally to extend the filter or custom filter inherit the Cachingfilter. The Cachingfilter feature can cache the contents of an HTTP response. This way, the granularity of the cached data is coarse, such as caching the entire page. Its advantages are simple to use, high efficiency, the disadvantage is not flexible enough, the degree of reusability is not high.
Ehcache uses the Simplepagecachingfilter class to implement the filter cache. This class inherits from Cachingfilter and has a default Calculatekey () method that generates the cache key, which uses the URI of the HTTP request and the query condition to form the key. You can also implement a filter yourself, inheriting the Cachingfilter class, and then overwrite the Calculatekey () method to generate a custom key.
Cachingfilter output data is gzip compressed based on the Accept-encoding header information sent by the browser.

There are two issues to be aware of when using gzip compression:
1. Filter uses the system default encoding for gzip compression, and for Chinese web pages that use GBK encoding, the language of the operating system needs to be set to: ZH_CN. GBK, otherwise there will be garbled problems.
2. By default, Cachingfilter determines whether gzip compression is done based on the accept-encoding parameter values that are included in the request headers sent by the browser. Although the Ie6/7 browser supports gzip compression, it does not take this parameter when sending a request. In order to IE6/7 can also be gzip compressed, can be inherited cachingfilter, to implement their own filter, and then in the specific implementation of the Acceptsgzipencoding method of overwrite.

protected boolean acceptsGzipEncoding(HttpServletRequest request) {boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");return acceptsEncoding(request, "gzip") || ie6 || ie7;}
Object/Method Cache

Object caching is to add the query data to the cache, the next time you query again directly from the cache, rather than go to the database query.
Object caching is generally for methods, classes, and the combination of spring's Aop objects, method caching is simple. There is a need for cutting programming, using spring Methodinterceptor or using @aspect.

Package Com.hoo.common.ehcache;import Java.io.serializable;import Net.sf.ehcache.Cache; Import Net.sf.ehcache.element;import Org.aopalliance.intercept.methodinterceptor;import Org.aopalliance.intercept.methodinvocation;import Org.apache.log4j.logger;import org.springframework.beans.factory.initializingbean;/** * <b>function:</b> Cache Method Interceptor Core code * @author Hoojo * @ CreateDate 2012-7-2 pm 06:05:34 * @file Methodcacheinterceptor.java * @package com.hoo.common.ehcache * @project Ehcache * @blog Http://blog.csdn.net/IBM_hoojo * @email [email protected] * @version 1.0 */public Class Methodcacheinterceptor imple ments Methodinterceptor, Initializingbean {private static final Logger log = Logger.getlogger (methodcacheinterceptor.c    LASS); PrivateCache Cache; public void Setcache (Cache Cache) {this.Cache=Cache; } public void Afterpropertiesset () throws Exception {Log.info (Cache+ "ACacheis required. Use Setcache (Cache) to provide one. ");} Public Object Invoke (Methodinvocation invocation) throws Throwable {String targetName = Invocation.getthis (). GETCL        (). GetName ();        String methodName = Invocation.getmethod (). GetName ();        object[] arguments = invocation.getarguments ();        Object result;        String CacheKey = Getcachekey (TargetName, methodName, arguments);        element element = null; Synchronized (this) {element =Cache. get (CacheKey); if (element = = null) {Log.info (CacheKey + "joins to cache:" +Cache. GetName ());                Call the actual method result = Invocation.proceed (); element = new Element (CacheKey, (Serializable) result);Cache. put (element); } else {Log.info (CacheKey + "using cache:" +Cache. GetName ());    }} return Element.getvalue ();     }/** * <b>function:</b> returns the exact method full path name parameter * @author Hoojo * @createDate 2012-7-2 06:12:39 * @param targetName Full path * @param methodName method name * @param arguments parameter * @return Full method name */Private Stri        Ng Getcachekey (String targetName, String methodName, object[] arguments) {stringbuffer sb = new StringBuffer (); Sb.append (TargetName). Append (".").        Append (MethodName);                if (arguments! = null) && (arguments.length! = 0)) {for (int i = 0; i < arguments.length; i++) { Sb.append (".").            Append (Arguments[i]);    }} return sb.tostring (); }}

The method interceptor here is primarily to intercept the method of the class you want to intercept, and then determine if the method's Classpath + method name + parameter value combination of the cache key exists in the cached caches. If it exists, remove the object from the cache and convert it to the return type we want. If not, add the object returned by the method to the cache. The idea is that the parameters of the current method and the object type of the return value need to be serialized.

We need to add Applicationcontext.xml in the SRC directory to complete the configuration of the Methodcacheinterceptor interceptor, which is the idea of injecting our cache object, which cache to manage the object cache, and then which classes, methods participate in the Interceptor's scan.

<context:component-scan base-package= "Com.hoo.common.interceptor"/> <!--Configure EH cache manager--><bean id= " CacheManager "class=" org.springframework.Cache. Ehcache. Ehcachemanagerfactorybean "/><!--Configure a simple cache factory Bean object--><bean id=" Simplecache "class=" Org.springframework.Cache. Ehcache. Ehcachefactorybean "> <property name=" CacheManager "ref=" CacheManager "/> <!--cache configuration using cache affinity Ehcache.xml- <property name= "CacheName" value= "Mobilecache"/></bean><!--Configure a cache interceptor object to handle the specific cache business-->< Bean id= "methodcacheinterceptor" class= "com. hoo.common.interceptor.MethodCacheInterceptor" > <property name= "Cache"Ref=" Simplecache "/></bean><!--the Pointcut object participating in the cache (Pointcut object, determining when and where to call the Interceptor)--><bean id=" Methodcachepointcut " Class= "Org.springframework.AOP. Support. Regexpmethodpointcutadvisor "> <!--configuration cacheAOPFacets--<property name= "advice" ref= "Methodcacheinterceptor"/> <!--Configure which methods participate in the cache policy-<!--                          . Represents any single character # # # + indicates that the previous character matches one or more # # # * Indicates a previous character 0 or more times # # # \escape symbols used by any regular expression--<!--. * denotes the preceding prefix (including the package name) Represents the Print method--<property Name= "Patterns" > <list> <value>com.hoo.rest.*restservice*    \.*get.*</value> <value>com.hoo.rest.*RestService*\.*search.*</value> </list> </property></bean> Add the following in the Ehcache.xmlCacheConfiguration <CacheName= "Mobilecache" maxelementsinmemory= "10000" eternal= "false" overflowtodisk= "true" timetoidl eseconds= "1800" timetoliveseconds= "3600" memorystoreevictionpolicy= "LFU"/>
Using the Ehcache cache in spring, hibernate

Ehcache is one of Hibernate's level two cache technology, can store the query data in memory or disk, save the next same query to query the database again, greatly reduce the database pressure;

1. Add the configuration in the Hibernate.cfg.xml configuration file, adding the following to the mapping tag in Hibernate.cfg.xml:

<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>  CacheCache Settings -->  <property name="hibernate.cache.use_second_level_cache">true</property>  <property name="hibernate.cache.use_query_cache">true</property>

2. If you are integrating in the spring configuration file, then you need to configure the configuration of the relevant sessionfactory in your Applicationcontext.xml

<prop key="hibernate.cache.use_query_cache">true</prop><prop key="hibernate.cache.use_second_level_cache">true</prop><prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

Then add the properties that use the cache in the Hibernate.cfg.xml configuration file

<!-- class-cache config -->  <class-cache class="com.hoo.hibernate.entity.User" usage="read-write" />

3. You can also include the following format information in the User.hbm.xml mapping file that requires the Cache 's Configuration class node:

<class name="com.hoo.hibernate.entity.User" table="USER" lazy="false"><cache usage="transactional|read-write|nonstrict-read-write|read-only" />

4. Configuring the cache using annotations

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   public class User implements Serializable {}

code example

Session s = HibernateSessionFactory.getSession();Criteria c = s.createCriteria(User.class);c.setCacheable(true);//这句必须要有System.out.println("第一次读取");List<User> users = c.list();System.out.println(users.size());HibernateSessionFactory.closeSession();s = HibernateSessionFactory.getSession();c = s.createCriteria(User.class);c.setCacheable(true);//这句必须要有System.out.println("第二次读取");users = c.list();System.out.println(users.size());HibernateSessionFactory.closeSession();

The second query does not print the SQL statement, but instead uses the objects in the cache directly.

The cache policy is based on:
    • Ehcache does not support transactional, the other three kinds can be supported.
    • Read-only: Without modification, it can be read-only cache, note: Under this policy, if you modify the database directly, even if you can see the foreground display, but modify the object to the cache will report error, thecache does not work. Another: Deleting a record will cause an error because the object in read-only mode cannot be deleted from the cache .
    • Read-write: The need to update the data, then use a read/write cache is appropriate, provided that the database is not serializable transaction isolation level (serialization of transaction isolation levels)
    • Nonstrict-read-write: Only occasionally need to update the data (that is, two transactions are not common to update the same record at the same time), and do not require very strict transaction isolation, it is more appropriate to use a non-strict read/write cache policy.

Java Cache Framework

Related Article

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.