Java cache component EhCache Getting Started tutorial

Source: Internet
Author: User

1. Technical background:

The system cache is an area of memory that resides between an application and a physical data source for temporary storage of replicated data in order to reduce the number of times an application accesses a physical data source, thereby improving the performance of the application. The cache assumes that the memory is limited, the cache is also limited in timeliness, so you can set the amount of memory can be executed by the failure algorithm, can be in full memory, in the case of the least access to the algorithm to remove the cache directly or switch to the hard disk.

Ehcache from hibernate, gradually covering all the functions of the cache, is currently the best development momentum of a project, with fast, simple, low consumption, strong scalability, support objects or serialization cache, support cache or element invalidation, provide LRU, Lfu and FIFO cache policies, which support memory cache and hard disk cache and distributed cache mechanism. Where the cache is stored in memory or disk (PS: No need to worry about capacity issues)

The class hierarchy of 2.EhCahe is introduced:

Mainly divided into three layers, the topmost is CacheManager, it is the entrance of Operation Ehcache. You can get a list of CacheManager by Cachemanager.getinstance () or create a new CacheManager from the CacheManager constructor. Each Cachemanger manages multiple caches. Each cache is associated with multiple element in a hash-like manner. element is where we store the cached content.

3. Environment Construction:

It's simple to put ehcache-2.1.0-distribution.tar.gz and ehcache-web-2.0.2-distribution.tar.gz squeezed jar packages into web-inf/lib.

Create an important configuration file Ehcache.xml, you can copy from the Ehcache component package, you can also build one, you need to put under classpath, generally put in/web-inf/classed/ Ehcache.xml; The specific configuration file can be searched online

4. Practical use

The first page of a site is estimated to be the most visited, we can consider to the homepage to do a cache;

Cache policy: should be fixed within a certain time, such as 2 minutes to update, to apply structure page-filter-action-service-dao-db as an example.

Location: page cache to do as close to the customer as possible, that is, between the page and the filter, the advantage is that the first user request, the page is cached, the second user in the request, go to the filter this request is over, need to go to action-service-dao-db , the benefit of course is that the server pressure is greatly reduced and the client page responds faster.

Home Page Cache survival time is set to 2 minutes, that is, the parameter timetoliveseconds (cache survival time) should be 120, at the same time timetoidleseconds (how long does not access the cache, it is clear that the cache) is best also set to 2 minutes or less than 2 minutes.

Then we look at the configuration of the Simplepagecachingfilter,

<filter><filter-name>indexCacheFilterfilter-name><filter-class> net.sf.ehcache.constructs.web.filter.simplepagecachingfilter<filter-class><filter>< filter-mapping><filter-name>indexcachefilterfilter-name><url-pattern>* Index.actionurl-pattern><filter-mapping>

Add the above code to Web. XML, then when you open the home page, you will find that 2 minutes before a bunch of SQL statements appear in the console, and can be adjusted to 5 minutes, in short, all under control.

Of course, if you like to cache some of the contents of the home page, you need to use the Simplepagefragmentcachingfilter filter, I look at:

<filter><filter-name>indexCacheFilterfilter-name><filter-class> net.sf.ehcache.constructs.web.filter.simplepagefragmentcachingfilter<filter-class>filter>< filter-mapping><filter-name>indexcachefilterfilter-name><url-pattern>*/index_right.jsp< Url-pattern><filter-mapping>

So we will JSP page through the Jsp:include to other pages, so that the effect of the page local cache, which seems to be no oscache tag useful.

In addition, there is a feature in Cachefilter, that is, the cache element is compressed, if the client browser support compression, filter will directly return the compressed stream, which saves bandwidth, the decompression work to the client to browse, Of course, if the client does not support gzip, then filter will take the cached elements out of the decompression back to the client browser (most crawlers do not support gzip, so the filter will be decompressed after the return stream).

In short, Ehcache is a very lightweight cache implementation, And since 1.2 support the cluster, and hibernate is the default cache provider, this article mainly introduces Ehcahe to the page cache support, but its function far more than this, to use good cache, the principle of cache in Java EE, the scope of application, Suitable scenarios and so on need a more profound understanding, so as to use the cache.

For everyone to deepen their understanding and use of the scene through practical examples, in an example of devotion:

* Use of Ehcache in spring

For any existing open source cache Framework, it is required to return results, such as get/find of the service or DAO layer in the cache system, if the data is updated (Create/update/delete is applied), Refreshes the corresponding contents in the cache.

According to the requirements, the plan applies spring aop+encache to achieve this function, and one of the reasons for using Ehcache is that spring provides encache support. There is no way of knowing why only supporting Ehcache and not supporting Oscache and Jbosscache.

AOP without interceptors, first create an interceptor that implements the Methodinterceptor interface, to intercept Service/dao method calls, to intercept the method, to search for the result of the method exists in the cache, if present, to return the result in the cache, Returns a database query result if it does not exist and returns the result to the cache.

public class Methodcacheinterceptor implements Methodinterceptor, Initializingbean{private static final Log logger = Logf Actory.getlog (Methodcacheinterceptor.class);p rivate cache cache;public void Setcache (cache cache) {This.cache = cache;} Public Methodcacheinterceptor () {super ();} /*** intercepts the Service/dao method and finds out if the result exists, returns the value in the cache if it exists, * Otherwise, returns the database query result and puts the query result in Cache*/public Object invoke ( Methodinvocation invocation) throws Throwable {String targetName = Invocation.getthis (). GetClass (). GetName (); String methodName = Invocation.getmethod (). GetName (); object[] arguments = invocation.getarguments (); Object result; Logger.debug ("Find object from Cache is" + cache.getname ()); String CacheKey = Getcachekey (TargetName, methodName, arguments); Element element = Cache.get (CacheKey); Page 26if (element = = null) {Logger.debug ("hold up Method, Get method result and create cache........!"); result = Invocation.proceed (); element = new Element (CacheKey, (Serializable) result); Cache.put (element); Return ElemeNt.getvalue ();} /*** the method of obtaining the cache key, the cache key is the unique identifier of an element in the cache * The cache key includes the package name + class name + method name, such as Com.co.cache.service.userserviceimpl.getalluser*/private string 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 ();} /*** implement Initializingbean, check if the cache is empty */public void Afterpropertiesset () throws Exception {Assert.notnull (cache, "Need a cache. Please use Setcache (Cache) to create it. ");}

The above code can be seen in the method invoke, complete the search cache/new cache function

Subsequently, the establishment of an interceptor methodcacheafteradvice, the role of the user in the Create/update/delete operation to refresh, remove the relevant cache content, This interceptor needs to implement the Afterretruningadvice interface and will execute after the intercepted method executes at Afterreturning (Object Arg0,method arg1,object[] Arg2,object arg3) The actions scheduled in the method

public class Methodcacheafteradvice implements Afterreturningadvice, Initializingbean{private static final Log logger = L Ogfactory.getlog (Methodcacheafteradvice.class);p rivate cache cache; Page 26public void Setcache (cache cache) {This.cache = cache;} Public Methodcacheafteradvice () {super ();} public void Afterreturning (object arg0, Method arg1, object[] arg2, object Arg3) throwsthrowable {String className = Arg3. GetClass (). GetName (); List List = Cache.getkeys (); for (int i = 0;i<list.size (); i++) {String CacheKey = string.valueof (List.get (i)); if ( Cachekey.startswith (ClassName)) {cache.remove (CacheKey); Logger.debug ("Remove cache" + CacheKey);}} public void Afterpropertiesset () throws Exception {assert.notnull (cache, "need a cache. Please use Setcache (Cache) to create it. ");}

This method obtains the full name of the target class, such as: Com.co.cache.test.TestServiceImpl, and then loops through the cache's key list, refreshing all the element in the/remove cache that is related to that class.

This is followed by configuring the properties of the Encache, such as the maximum number of caches, the cache refresh time, and so on.

<ehcache><diskstore path= "C:\\myapp\\cache"/><defaultcachemaxelementsinmemory= "eternal=" False "timetoidleseconds=" timetoliveseconds= "overflowtodisk=" true "/><cache name=" Default_cache " Maxelementsinmemory= "10000" eternal= "false" timetoidleseconds= "300000" timetoliveseconds= "600000" overflowToDisk= " True "/></ehcache>

It is important to note that Defaultcache defines a default cache, which cannot be deleted, otherwise it throws no default cache is configured exception. Also due to the use of interceptors to refresh the cache content, so in the definition of the cache life cycle can define a larger value, timetoidleseconds= "30000000", timetoliveseconds= "6000000", as if not large enough?

The cache and two interceptors are then configured in spring's configuration file Cache.xml, and two "pointcuts" are created to intercept different method names. You configure Application.xml and import Cache.xml. Such a simple Spring+encache framework will be built to complete.

Because of the time relationship introduced here, the opportunity will also introduce the use of Ehcache in the distributed cluster system, thank you.
Transferred from: http://blog.csdn.net/yangchao228/article/details/7027485

Java cache component EhCache Getting Started tutorial

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.