Use Spring AOP to configure and manage your second-level cache (ehcache) records for query

Source: Internet
Author: User
Use Spring AOP to configure and manage your second-level cache (ehcache) records for query
Use Spring AOP to configure and manage your level 2 cache (ehcache)
If spring + Hibernate is used in our project, we will first think of the ehcache cache tool that comes with spring, the popular Cache Policy ehcache has been integrated in spring. Currently, many cache policies such as Oscache and memcached are used. these should be the most used cache tools currently.
In a framework like spring + hibernate, ehcache should be a level-2 Cache. We know that a level-1 cache is used by default in hibernate, that is, in session. The second-level cache should be within the sessionfactory range. The second-level cache does not work by default, which requires a simple configuration.
Before configuration, I would like to explain that caching can theoretically improve the performance of your website system, but the premise is that you must ensure that you have a good architecture design. For example, if a single server is used for a system built with spring + hibernate, it would be better to use the ehcache of spring for second-level cache. If your system is a distributed system with multiple servers, memcached is the best choice. Generally, memcached performs caching better than ehcache and Oscache, but not all websites use memcached to get twice the result with half the effort. Although it is better, it has a premise that you have multiple servers and are distributed. In this way, memcached is used to improve the system performance. Because memcached is a "distributed" Memory Object cache system, that is, applications that do not need to be "distributed", do not need to be shared, or simply have to be small to only one server, memcached will not bring any benefits. On the contrary, it will slow down the system efficiency because resources are also required for network connections. the Oscache cache mechanism has fewer restrictions. It is similar to ehcache.
Integrating ehcache in spring + hibernate requires only three simple steps.
Step 1: configure the cache file ehcache. xml and put it in the src directory by default. The following is a simple configuration.

XML Code

There is a default cache configuration and a self-configured cache. If the cache is not specified in the application, the default configuration attribute is used by default.
Step 2: Use the powerful mechanism in spring to design AOP for aspect. to compile two class files, methodcacheafteradvice. java (mainly synchronous updates to dirty things) and methodcacheinterceptor. java (mainly uses the Interceptor to create a cache and cache the objects to be cached ). The implementation mechanism of the interceptor is actually a common filter. It works like a filter. The following are the two files.
Methodcacheinterceptor. Java

Java code
Public class methodcacheinterceptor implements methodinterceptor,
Initializingbean {
Private Static final log logger = logfactory
. Getlog (methodcacheinterceptor. Class );
Private cache;
Public void setcache (Cache cache ){
This. cache = cache;
}
Public methodcacheinterceptor (){
Super ();
}
/**
* Intercept the service/DAO method and check whether the result exists. If yes, return the value in the cache. Otherwise, return the database query result and put the query result into the 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 );
Long starttime = system. currenttimemillis ();
If (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 );
Long endtime = system. currenttimemillis ();
The logger.info (targetname + "." + methodname + "method is called for the first time and cached. Time consumed"
+ (Endtime-starttime) + "millisecond" + "cachekey :"
+ Element. getkey ());
} Else {
Long endtime = system. currenttimemillis ();
Logger.info (targetname + "." + methodname + "results are directly called from the cache. Time consumed"
+ (Endtime-starttime) + "millisecond" + "cachekey :"
+ Element. getkey ());
}
Return element. getvalue ();
}
/**
* Obtain 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, and parameter.
*/
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
Propagation_required Propagation_required Propagation_required Propagation_required, readonly Propagation_required, readonly Classpath: ehcache. xml Default_cache . * Find .* . * Get .* . * Create .* . * Update .* . * Delete .* * Dao Methodcachepointcut Methodcachepointcutadvice Transactioninterceptor Propagation_required Propagation_required Propagation_required Propagation_required, readonly Propagation_required, readonly Classpath: ehcache. xml Default_cache . * Find .* . * Get .* . * Create .* . * Update .* . * Delete .* * Dao Methodcachepointcut Methodcachepointcutadvice Transactioninterceptor
The above code intercepts and caches the DaO layer. It is better to intercept the DaO layer. You can refer to the specific design of your system. If there is no business layer, you can also intercept the DaO layer. The interception is configured with a regular expression. The find and get methods are only cached. If the CREATE, update, and delete methods are used, the cache is synchronized. It is best not to use cache for some frequent operations. The cache is used for operations that do not change frequently.
Only three simple steps can be used to complete ehcache. Try it yourself. I have not explained the methods in detail. In fact, it is very simple. You can see it later. Sorry for the improper handling.

Article Source: DIY tribe (http://www.diybl.com/course/1_web/webjs/2008410/109598.html)

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.