Detailed description of Ehcache configuration for hibernate second-level cache

Source: Internet
Author: User

1. Introduction to hibernate Cache

Session: Internal Cache
Transaction scope: the cache can only be accessed by the current transaction. The cache lifecycle depends on the transaction lifecycle. When the transaction ends, the cache ends the lifecycle.
 
SessionFactory ):
The cache is shared by all transactions within the application scope. These transactions may access the cache concurrently, so the cache must be updated. The cache lifecycle depends on the application lifecycle. When the application ends, the cache ends, and the second-level cache exists in the application scope. Cluster scope: in a cluster environment, the cache is shared by processes of one or more machines. Data in the cache is replicated to every process node in the cluster environment. Data Consistency in the cache is ensured through remote communication between processes. Data in the cache is usually in the form of loose data of objects, the second-level cache also exists and has application scope.
 
Note: For most applications, you should carefully consider whether to use the cluster cache. In addition, the cluster scope also has data synchronization issues, so use it with caution. The persistence layer of various cache processing processes can provide multiple caches. If no data is found in the cache of the transaction range, you can also query it in the cache of the application range or cluster range. If no data is found, you can only query it in the database.
 
The principle of using second-level cache:
◆ Data will not be modified by a third party
◆ The same data system is often referenced
◆ The data size is within the acceptable range
◆ Key data or data that will not be concurrently updated
 

II. Introduction to EhCache

EHCache is a lightweight cache implementation. It is a pure Java in-process cache framework and supports clusters SINCE 1.2. It is the default CacheProvider in Hibernate.

Ehcache can be used directly because it is fast and capable of excellent performance.

It can also be used in combination with the Hibernate object/link framework. Objects, Data, jsp, and Servlet can be cached.

Cache storage: memory or disk.

 

Iii. Configuration

1, first go to the official website to download the ehcache-core.jar, ehcache-web.jar the latest version, and then add the project lib

2. Add the following to the hibernate Configuration:

<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>
<Prop key = "hibernate. cache. provider_configuration_file_resource_path">/ehcache. xml </prop>

3. In the ing file *. hbm. xml, add the following under the <class name = "" table = ""> node:

<! -- Cache Policy -->
<Cache usage = "read-write"/>

4. Add the ehcache. xml file to the src root directory. The specific content is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Ehcache>

<! -- Data cache directory -->
<DiskStore path = "/jcms_cache_data/ehcache"/>
<! --
Page Cache
Three cache algorithms: LRU-least recently used, LFU-less frequently used, and FIFO.

Parameters:

SimplePageCachingFilter cache name
Maximum number of elements in maxElementsInMemory Cache
Maximum number of cache elements that maxElementsOnDisk persists to the hard disk
Eternal = "false" if it is true, it indicates that the object will never expire. The timeToIdleSeconds and timeToLiveSeconds attributes are ignored. The default value is false;
OverflowToDisk = "true" when the number of elements in the cache exceeds the limit, these elements are persisted to the hard disk. If it is false, the setting is meaningless.
How long does timeToIdleSeconds not access the cache?
Survival time of timeToLiveSeconds Cache
-->
<Cache name = "SimplePageCachingFilter"
MaxElementsInMemory = "10000"
Maxelementsondisk= "1000"
Eternal = "false"
OverflowToDisk = "true"
TimeToIdleSeconds = "5"
TimeToLiveSeconds = "30"
MemoryStoreEvictionPolicy = "LFU"/>
 
<! -- Use the following configuration for Ehcache objects and data cache -->
<DefaultCache maxElementsInMemory = "10000"
Eternal = "false"
TimeToIdleSeconds = "120"
TimeToLiveSeconds = "120"
OverflowToDisk = "true"
DiskSpoolBufferSizeMB = "30"
Maxelementsondisk= "10000000"
DiskPersistent = "false"
DiskExpiryThreadIntervalSeconds = "120"/>
</Ehcache>

5. Add the following configuration to web. xml:

<! -- Ehcache page cache configuration -->
<Filter>
<Filter-name> PageCacheFilter </filter-name>
<Filter-class> net. cnki. tpi. cms. util. PageCacheFilter </filter-class>
<! -- The initialization parameters are URLs that do not need to be cached. Multiple initialization parameters are separated by commas. -->
<Init-param>
<Param-name> notCacheUrlList </param-name>
<Param-value>/jcms/pcons/getUserManager. action </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-name> PageCacheFilter </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

 

5. Write a Filter that inherits SimplePageCachingFilter, as shown below:

[Java]

 
Package net. cnki. tpi. cms. util;
Import java. util. Enumeration;
 
Import javax. servlet. FilterChain;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
 
Import net. sf. ehcache. CacheException;
Import net. sf. ehcache. constructs. blocking. LockTimeoutException;
Import net. sf. ehcache. constructs. web. AlreadyCommittedException;
Import net. sf. ehcache. constructs. web. AlreadyGzippedException;
Import net. sf. ehcache. constructs. web. filter. FilterNonReentrantException;
Import net. sf. ehcache. constructs. web. filter. SimplePageCachingFilter;
 
Import org. apache. log4j. Logger;
 
Public class PageCacheFilter extends SimplePageCachingFilter {
Private final static Logger log = Logger. getLogger (PageCacheFilter. class );
Private final static String NOT_CACHE_URL_LIST = "notCacheUrlList ";
Private static String [] notCacheURLs;

Private void init () throws CacheException {
String notCacheUrlList = filterConfig. getInitParameter (NOT_CACHE_URL_LIST );
If (! MyStringUtil. isNullOrEmpty (notCacheUrlList )){
NotCacheURLs = notCacheUrlList. split (",");
}
}

@ Override
Protected void doFilter (final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws injection, AlreadyCommittedException, FilterNonReentrantException, LockTimeoutException, Exception
{
If (notCacheURLs = null ){
Init ();
}
String request_url = request. getRequestURI ();
Boolean flag = false;

If (notCacheURLs! = Null & notCacheURLs. length> 0 ){
For (String notCacheURL: notCacheURLs ){
If (request_url.contains (notCacheURL. trim ())){
Flag = true;
Break;
}
}
}
// If the requested url does not need to be cached, the normal page turns to be executed; otherwise, the page is cached.
If (flag ){
Chain. doFilter (request, response );
} Else {
String query = request. getQueryString ();
If (query! = Null ){
Query = "? "+ Query;
}
Log.info ("current request cached:" + request_url + query );
Super. doFilter (request, response, chain );
}
}

@ SuppressWarnings ("unchecked ")
Private boolean headerContains (final HttpServletRequest request, final String header, final String value ){
LogRequestHeaders (request );
Final Enumeration accepted = request. getHeaders (header );
While (accepted. hasMoreElements ()){
Final String headerValue = (String) accepted. nextElement ();
If (headerValue. indexOf (value )! =-1 ){
Return true;
}
}
Return false;
}

@ Override
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;
}
}

 

 

 

 

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.