Ehcache Usage Details

Source: Internet
Author: User

From: http://1985wanggang.blog.163.com/blog/static/7763833200991463348350/

1. What is ehcache?


Ehcache is one of hibernate's second-level cache technologies. It can store the queried data in memory or disk, saving the need to query the database again with the same query statement next time, greatly reducing the database pressure;

2. ehcache usage notes


When you use hibernate to modify table data (save, update, delete, and so on), ehcache will automatically delete all the caches related to this table (this can achieve synchronization ). However, for tables that frequently modify data, the significance of caching may be lost (the database pressure cannot be reduced );

3. ehcache usage


3.1 less updated table data

Generally, ehcache should be used for tables with less write operations (including update, insert, delete, and so on) [This is also the case for hibernate's second-level cache];
3.2 not strict requirements on concurrency

The cache of the two machines cannot be synchronized in real time;

4. Implementation in the project


4.1 Add the ehcache. xml file to the src directory of the project. The content is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>
<Ehcache>
<Diskstore Path = "Java. Io. tmpdir"/>
<Defaultcache maxelementsinmemory = "5" <! -- Total number of records that can be stored in the cache -->

Eternal = "false" <! -- Whether the cache will never be destroyed -->

Overflowtodisk = "true" <! -- Whether to write the cached data to the disk when the cached data reaches the maximum value -->

Timetoidleseconds = "15" <! -- When the cache idle time exceeds this value, the cache is automatically destroyed -->

Timetoliveseconds = "120" <! -- After the cache is created, it is automatically destroyed when it reaches the cache -->

/>
</Ehcache>
4.2 above the ing tag in hibernate. cfg. xml
Add the following content:

<Property name = "show_ SQL"> true </property>
<Property name = "hibernate. cache. provider_class"> org. hibernate. cache. ehcacheprovider </property>
<Property name = "hibernate. cache. use_query_cache"> true </property>
4.3 Add the following content to the class label in the HBM. xml file of the bean to be cached:

<Cache Usage = "read-only"/> <! -- Or read/write -->

4.4 create a Dao with the following content:

Session S = hibernatesessionfactory. getsession ();
Criteria c = S. createcriteria (XYZ. Class );
C. setcacheable (true); // This sentence must have

System. Out. println ("first read ");
List L = C. List ();
System. Out. println (L. Size ());
Hibernatesessionfactory. closesession ();

S = hibernatesessionfactory. getsession ();
C = S. createcriteria (XYZ. Class );
C. setcacheable (true );
// This sentence must have

System. Out. println ("second read ");
L = C. List ();
System. Out. println (L. Size ());
Hibernatesessionfactory. closesession ();
4.5 then you will see the printed information as (indicating that the database has not been read for the second time ):

First read
Hibernate :*******
13
Second read
13

Configure spring + hibernate to use ehcache as second-level cache

A large amount of data flow is a common cause of Web application performance problems, and cache is widely used to optimize database applications. The cache is designed to reduce applications by saving the load data from the database.
And Data
Data Flow between databases. Database Access is required only when the retrieved data is not available in the cache. Hibernate can use two different object caches: first-level
Cache and second-level cache. First-level cache is associated with the session object, while second-level
Cache is associated with the session factory object.

By default, Hibernate uses the first-level cache based on each transaction.
.
Hibernate uses first-level
Cache mainly reduces the number of SQL queries in a transaction. For example, if an object is modified multiple times in the same transaction, Hibernate generates only one
Update SQL statement. To reduce data flow, second-level cache
The load objects are maintained between different transactions at the factory level. These objects are available to the entire application, not just the queries currently running by the current user. In this way, each query returns
To avoid one or more potential database transactions.

DownloadEhcache


, Hibernate3.2 must be ehcache1.2 or later. You can modify the log4j configuration file log4j.logger.net. SF. hibernate. cache = debug to view the log.

1. ehcache. xml:

<Ehcache>

<! -- Sets the path to the directory where cache. data files are created.

If the path is a Java System property it is replaced
Its value in the running VM.

The following properties are translated:
User. Home-user's home directory
User. dir-user's current working directory
Java. Io. tmpdir-default temp file path -->
<Diskstore Path = "Java. Io. tmpdir"/>

<! -- Default cache configuration. These will applied to caches programmatically created through
The cachemanager.

The following attributes are required:

Maxelementsinmemory-sets the maximum number of objects that will be created in memory
Eternal-sets whether elements are eternal. If eternal, timeouts are ignored and
Element is never expired.
Overflowtodisk-sets whether elements can overflow to disk when the in-memory cache
Has reached the maxinmemory limit.

The following attributes are optional:
Timetoidleseconds-sets the time to idle for an element before it expires.
I. e. the maximum amount of time between accesses before an element expires
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that an element can idle for infinity.
The default value is 0.
Timetoliveseconds-sets the time to live for an element before it expires.
I. e. the maximum time between creation time and when an element expires.
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that and element can live for infinity.
The default value is 0.
Diskpersistent-whether the disk store persists between restarts of the virtual machine.
The default value is false.
Diskexpirythreadintervalseconds-the number of seconds between runs of the disk expiry thread. The default value
Is 120 seconds.
-->

<Defaultcache
Maxelementsinmemory = "10000"
Eternal = "false"
Overflowtodisk = "true"
Timetoidleseconds = "120"
Timetoliveseconds = "120"
Diskpersistent = "false"
Diskexpirythreadintervalseconds = "120"/>


<! -- See
Http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how
Configure caching for your objects -->
</Ehcache>

2. hibernate sessionfactory configuration in the applicationContext-hibernate.xml:

<! -- Hibernate sessionfactory -->
<Bean id = "sessionfactory" class = "org. springframework. Orm. hibernate3.localsessionfactorybean">
<Property name = "datasource" ref = "datasource"/>
<Property name = "configlocation"> <value> classpath: hibernate. cfg. xml </value> </property>
<! -- The property below is commented out B/c it doesn't work when run
Ant in eclipse. It works fine for individual JUnit tests and in idea ??
<Property name = "mappingjarlocations">
<List> <value> file: Dist/appfuse-dao.jar </value> </List>
</Property>
-->
<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect"> @ hibernate-dialect @ </prop>
<! -- <Prop key = "hibernate. show_ SQL"> true </prop> -->
<Prop key = "hibernate. max_fetch_depth"> 3 </prop>
<Prop key = "hibernate. hibernate. use_outer_join"> true </prop>
<Prop key = "hibernate. JDBC. batch_size"> 10 </prop>
<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. use_ SQL _comments"> false </prop>
-->
<! -- Create/update the database tables automatically when the JVM starts up
<Prop key = "hibernate. hbm2ddl. Auto"> Update </prop> -->
<! -- Turn batching off for better error messages under PostgreSQL
<Prop key = "hibernate. JDBC. batch_size"> 0 </prop> -->
</Props>
</Property>
<Property name = "entityinterceptor">
<Ref local = "auditloginterceptor"/>
</Property>
</Bean>
Description
Note: If you do not set "query cache", Hibernate only caches a single Persistent object obtained using the load () method. If you want to cache the object, use findall (),
If you obtain the data result set by using methods such as List (), iterator (), createcriteria (), and createquery (), you must set
Hibernate. cache. use_query_cache is true.

3. XDoclet is used in the model class to generate the cache xml tag in *. HBM. XML, that is, <Cache Usage = "read-only"/>

/**
* @ Hibernate. Class table = "wf_workitem_his"
* @ Hibernate. Cache Usage = "read-write"
*
*/

4. For "query cache", it must be encoded in the program:

Gethibernatetemplate (). setcachequeries (true );
Return gethibernatetemplate (). Find (hql );

Configure ehcache and query cache using spring and Hibernate
1. applicationcontext. xml
<Prop key = "hibernate. cache. provider_class"> org. hibernate. cache. ehcacheprovider </prop>
<Prop key = "hibernate. cache. use_query_cache"> true </prop>

These two statements are added to hibernateproperties.
<Bean id = "hibernatetemplate" class = "org. springframework. Orm. hibernate3.hibernatetemplate">
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
<Property name = "cachequeries">
<Value> true </value>
</Property>
</Bean>

Add the bean to applicationcontext. xml. In the beans of each DAO, the changes are as follows:
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
Change
<Property name = "hibernatetemplate">
<Ref bean = "hibernatetemplate"/>
</Property>

2. Put the ehcache. xml file in the root directory of classes.

3. Configuration relationship between pojo and ehcache. xml
Take com. Ce. ceblog. pojos. ceblogjournal as an Example
Configure in ceblogjournal. HBM. xml:
<Class name = "ceblogjournal" table = "ceblog_journal" lazy = "false">
<Cache Usage = "read-write" region = "attribute value of name in ehcache. xml"/>
Note: This sentence must be followed by the class label. Other positions are invalid.

The entity of the ehcache. xml file is as follows:
<Defaultcache maxelementsinmemory = "10000"
Eternal = "false" timetoidleseconds = "1" timetoliveseconds = "1"
Overflowtodisk = "true"/>
<Cache
Name = "com. Ce. ceblog. pojos. ceblogjournal" maxelementsinmemory = "10000"
Eternal = "false" timetoidleseconds = "300" timetoliveseconds = "600"
Overflowtodisk = "true"/>
How to find the cache method name for HBM files
Omitted: if you do not specify the attribute value of name in the HBM file "region =" ehcache. xml ", use the name
Com. Ce. ceblog. pojos. ceblogjournal cache. If no cache name matches the class name, use
Defaultcache.
If ceblogjournal contains a set, you need to specify its cache
For example, if ceblogjournal contains the ceblogreplyset set
Add the following configuration to ehcache. xml:
<Cache name = "com. Ce. ceblog. pojos. ceblogjournal. ceblogreplyset"
Maxelementsinmemory = "10000" Eternal = "false" timetoidleseconds = "300"
Timetoliveseconds = "600" overflowtodisk = "true"/>

In addition, the query cache configuration is as follows:
<Cache name = "org. hibernate. cache. updatetimestampscache"
Maxelementsinmemory = "5000"
Eternal = "true"
Overflowtodisk = "true"/>
<Cache name = "org. hibernate. cache. standardquerycache"
Maxelementsinmemory = "10000"
Eternal = "false"
Timetoliveseconds = "120"
Overflowtodisk = "true"/>

4. Cache Policy Selection basis:
<Cache Usage = "transactional | read-write | nonstrict-read-write | read-only"/>
Ehcache does not support transactional. The other three types are supported.
Read-Only: you do not need to modify it, so you can perform read-only caching on it. Note that in this policy, if you directly modify the database, even if you can see the front-end display effect, however, when an object is modified to the cache, an error is reported, and the cache does not work. In addition, an error is returned when deleting a record because the read-only mode object cannot be deleted from the cache.
Read-write: to update data, it is more appropriate to use the read/write cache. premise: the database cannot think of serializable transaction isolation level (serialization transaction isolation level)
Nonstrict-read-write: Only data needs to be updated occasionally (that is, it is uncommon for two transactions to update the same record at the same time), and strict transaction isolation is not required, therefore, it is more suitable to use non-strict read/write cache policies.

5. Use log4j.logger.org of log4j during debugging. hibernate. cache = debug, which makes it easier to see the ehcache operation process. It is mainly used for debugging. comment out the actual application release process to avoid performance impact.

6. When ehcache is used, it is normal to print the SQL statement. Because the query cache is set to true, two cache regions are created: one for saving the query result set.
(Org. hibernate. cache. standardquerycache );
The other is used to save the timestamp (Org. hibernate. cache. updatetimestampscache) of a series of recently queried tables ). Note: When querying
In the cache, it does not cache the exact state of the objects contained in the result set; it only caches the values of the Identifier attributes of these entities and the results of each value type. You need to print the SQL statement and the latest Cache
Compare the content and modify the differences to the cache. Therefore, the query cache is usually used together with the second-level cache.

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.