Rational use of Ehcache

Source: Internet
Author: User

       ehcache is an open source project to SourceForge (http://ehcache.sourceforge.net/), is a pure Java implementation of simple, fast cache components. You can cache pages, objects, data, and support clustered/distributed caching. If the integration of spring and Hibernate is also very simple, spring's support for Ehcache is also very good. Ehcache supports memory and disk caching, supports LRU, LFU, and FIFO multiple elimination algorithms, supports distributed cache, and can be used as a hibernate caching plugin. It can also provide cache based on filter, which caches the content of the response and uses GZIP compression to improve response speed. Use the S2SH development website, the homepage needs to display the data to be many, the visit quantity is big. If do not do processing, then frequently query the database, the result is the page display slow, server, database overwhelmed. If the Site page shows the data is not particularly frequent updates, want to improve the speed of page display, reduce the burden on the server, you should consider using caching.

What's 1.EhCache?
Ehcache is one of the two-level caching techniques of hibernate, which can store the queried data in memory or disk, save the next query database again, and greatly reduce the database pressure;

The use of 2.EhCache attention points
When you modify the table data (Save,update,delete, and so on) in a hibernate way, Ehcache automatically deletes all the caches in the cache for this table (so that synchronization can be achieved). But for tables that are often modified by the data, caching may be lost (not to reduce database pressure);

3.EhCache use of the occasion
3.1 Less Update table data
Ehcache are typically used in tables (including Update,insert,delete, etc.) where write operations are less performed [Hibernate's Level two cache is the same];
3.2 Not very strict concurrency requirements
The cache in two machines cannot be synchronized in real time;
3.3 In terms of s2sh, there are two ways to do caching:
1 Enable the Hibernate level two cache. 2 Use page caching.
3.4 There is a principle to use caching:
The higher the cache effect, the better. It is recommended that you use page caching.


4.EhCache Concept Understanding (Ehcache.xml Interpretation)

<?xml version= "1.0" encoding= "UTF-8"?>
<ehcache>
	<diskstore path= "Java.io.tmpdir"/>
	
	<defaultcache 
		maxelementsinmemory= "" eternal= " 
		false" 
		timetoidleseconds= 
		" timetoliveseconds= "1200" 
		overflowtodisk= "true"/>
	
	<cache name= 
		"Testcache1" 
		maxelementsinmemory= "Eternal=" " 
		false" 
		timetoliveseconds= "36000" 
		timetoidleseconds= "3600" 
		overflowtodisk= "true"/> 
</ehcache>

4.1 maxelementsinmemory
such as maxelementsinmemory= "10000", the number of objects stored in memory, the maximum number of cached elements in memory management limit.

4.2 Overflowtodisk
Whether the overflowtodisk= "true" object is written to the hard disk when it reaches the maximum number in memory.

4.3 Eternal
such as eternal= "false" indicates whether an object in the cache is out of date, defaults to expiration (according to the time in the configuration), and, if changed to true, indicates that the object never expires. That is, the elements in the cache are kept in memory and are not lost because of time out, so the values of the Timetoidleseconds and timetoliveseconds two properties do not work when the value is true.

4.4 Maxelementsondisk
such as maxelementsondisk= "10000000" on the hard disk on the maximum number of objects, hard disk management of the cache element maximum limit value. The default value is 0, which means there is no limit.

4.5 Timetoidleseconds
For example, timetoidleseconds= "3600" sets the time that an element is idle before it expires and is valid only for Non-persistent cache objects. That is, how long to not access the cache, then Ehcache clears the cache. The default value is 0, and a value of 0 means that the element can be idle for an indefinite length of time.

4.6 Timetoliveseconds
such as timetoliveseconds= "100000" set the element from creation to expiration time. The number of seconds an object survives expires. The default value is 0, and a value of 0 means that the element can survive for an indefinite length of time. This means that from the time the cache is created to extinction, the element is timed from creation, and when this time is exceeded, it is removed from the cache.

4.7 diskpersistent
If diskpersistent= "false" persists the disk cache, sets whether disk storage is performed when the virtual machine restarts, and defaults to false. To really persist the cache to disk, it is important to note when writing a program that the Void Flush () method is used after the Net.sf.ehcache.Cache void put (element Element) method is used.

4.8 diskexpirythreadintervalseconds
such as diskexpirythreadintervalseconds= "1000": Access to disk thread activity time.

4.9 diskspoolbuffersizemb
The size of the buffer when it is saved to disk, the default 30MB, and each cache has its own buffer.

4.10 Emorystoreevictionpolicy
such as emorystoreevictionpolicy= "LRU", the element evicted from the cache rule. There are three species, (LRU) The least recently used (cached element has a timestamp, when the cache is full and needs to make room to cache new elements), the elements in the existing cache element that have the time stamp away from the current time are cleared out of the cache, for default. First-in-out (FIFO), first-in. Less frequently Used (specified as LFU) is the least used (straightforward point is always the least used.) As mentioned above, the cached element has a hit attribute, and the minimum hit value will be cleared out of the cache.

4.11 Name
Specify a cache name to identify the different cache, must be unique.

The attributes that must be filled in are: maxelementsinmemory Maxelementsondisk eternal Overflowtodisk

5.EhCache Page Caching Application
There is no doubt that almost all the homepage of the website is the highest access rate, and the data source on the home page is very extensive, most of them come from different objects, and may come from different db, so it is a good idea to do caching on the home page, so what is the caching strategy of the homepage? I think it should be the same for a fixed period of time, say 2 minutes update. So where does this cache go, let's take a look at it, assuming that your application's structure is page-filter-action-service-dao-db, and that the place in the process is where you can cache, depending on the characteristics of the page cache, The page should be cached as close to the customer's place, that is, between page and filter, the advantage is that the first user request, the page is cached, the second user again to request, go to filter this request is over, No need to go back to the action-service-dao-db. The benefit is the reduction of server pressure and the speed of Customer segment page response.

And then we'll look at the configuration of Simplepagecachingfilter,

<filter>

        <filter-name>indexCacheFilter<filter-name>

        <filter-class>

            Net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter

        <filter-class>

<filter>

<filter-mapping>

        <filter-name>indexCacheFilter<filter-name>

        <url-pattern>* Index.action<url-pattern>

<filter-mapping>

Just need so many steps, we can give a page to do a cache, put the above configuration into your web.xml, then when you open the home page, you will find that 2 minutes will have a bunch of SQL statements appear on the console. Of course you can also adjust to 5 minutes, in short, everything is under control.

Well, caching the entire page looks very simple, not even need to write a line of code, only a few lines of configuration on the line, simple enough, although it looks simple, but in fact the internal implementation is not simple oh, interested, You can look at the source code of the Simplepagecachingfilter inheritance system.

The above configuration for the situation is to cache the entire home page, if you want to cache the first part of the content, you need to use simplepagefragmentcachingfilter this filter. Let's take a look at the following fragment:

<filter>

        <filter-name>indexCacheFilter<filter-name>

        <filter-class>

            Net.sf.ehcache.constructs.web.filter.SimplePageFragmentCachingFilter

       <filter-class>

<filter >
<filter-mapping>

        <filter-name>indexCacheFilter<filter-name>

        <url-pattern >*/index_right.jsp<url-pattern>

<filter-mapping>
This JSP needs to be jsp:include to other pages, so that the local page is cached. This seems to have no oscache tag easy to use.

In fact, there is a feature in the Cachefilter, that is, gzip, that is, the elements of the cache is compressed, if the client browser support compression, filter will directly return the compressed flow, so that the bandwidth savings, the decompression of the work to the client browser, If the customer's browser does not support gzip, then filter will take the cached elements out of the decompression and then return to the client browser (most reptiles do not support gzip, so filter will be extracted and then return to the stream), the advantage is to save bandwidth, The disadvantage is that it increases the burden on the client's browser (but I think this is a very small burden for contemporary computers).

Well, if your page just needs to use the page cache, you may want to consider ehcache, because it is very simple and easy-to-use.

6.EhCache API (caching is basically configuration-oriented)
CacheManager main Cache Management class, a general application for an instance, as follows
Cachemanager.create (), or you can use the new CacheManager method to create
The default profile is a Ehcache.xml file, or you can use a different configuration: CacheManager manager = new CacheManager ("Src/config/other.xml");

caching is created in an automated manner

CacheManager Singletonmanager = Cachemanager.create ();
Singletonmanager.addcache ("Testcache");
Cache test = Singletonmanager.getcache ("Testcache");

Or create a cache directly


CacheManager Singletonmanager = Cachemanager.create ();
Cache Memoryonlycache = new cache ("Testcache", 5000, False, False, 5, 2);
Manager.addcache (Memoryonlycache);
Cache test = Singletonmanager.getcache ("Testcache");

Delete Cache

CacheManager Singletonmanager = Cachemanager.create ();
Singletonmanager.removecache ("SampleCache1");

After you use Ehcache, you need to close

Cachemanager.getinstance (). Shutdown ()

The use of caches


Cache cache = Manager.getcache ("SampleCache1");

Perform CRUD operations


Cache cache = Manager.getcache ("SampleCache1");
element element = new Element ("Key1", "value1");
Cache.put (Element);

Update

Cache cache = Manager.getcache ("SampleCache1");
Cache.put (New Element ("Key1", "value1");
This is updates the entry for "Key1"
Cache.put (New Element ("Key1", "value2");

Get Serializable


Cache cache = Manager.getcache ("SampleCache1");
Element element = Cache.get ("Key1");
Serializable value = Element.getvalue ();

Get non serializable

Cache cache = Manager.getcache ("SampleCache1");
Element element = Cache.get ("Key1");
Object value = Element.getobjectvalue ();

Remove

Cache cache = Manager.getcache ("SampleCache1");
element element = new Element ("Key1", "value1"
Cache.remove ("Key1");

The use of 7.EhCache in S2sh

1, download Ehcache web version http://ehcache.org/downloads/catalog note Download the Web version. Visible Attachments

2, decompression will Ehcache-web-2.0.3.jar, Ehcache-core-2.3.0.jar into the lib.

3, establish ehcache.xml under SRC

4, start configuring Web.xml, Note that this filter configuration should be placed in front of the Struts2 core filter.

<!--page cache configuration Ehcache-->
	<filter>
		<filter-name>simplepagefragmentcachingfilter</ Filter-name>
		<filter-class>net.sf.ehcache.constructs.web.filter.simplepagefragmentcachingfilter </filter-class>
		<init-param>
			<param-name>suppressStackTrace</param-name>
			<param-value>false</param-value>
		</init-param>
		<init-param>
			<param-name >cacheName</param-name>
			<param-value>SimplePageFragmentCachingFilter</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name> Simplepagefragmentcachingfilter</filter-name>
		<url-pattern>/index.action</url-pattern>
	</filter-mapping>

5, configure Ehcache.xml

<?xml version= "1.0" encoding= "UTF-8"?>

<ehcache xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
         xsi:nonamespaceschemalocation= " Ehcache.xsd "
         updatecheck=" true "monitoring=" AutoDetect "
         dynamicconfig=" true ">
         <diskstore path= "Java.io.tmpdir"/>
         <cache name= "Simplepagefragmentcachingfilter"
  		maxelementsinmemory= "ten"
  		Eternal= "false"
  		timetoidleseconds= "10000"
  		timetoliveseconds= "10000"
  		overflowtodisk= "true" >
	</cache>
</ehcache>
Restart the server, run the page, the first access query the database, at this time ehcache the content of the page cache, the next visit, then directly use the data in the cache, without having to access the database. Until the cache expires, the database will not be queried again.

Summary: Ehcache is a very lightweight cache implementation and supports clustering since 1.2, the current version is 1.3, and the hibernate default cache provider. Although this article is the introduction of Ehcache to the page cache support, but the Ehcache function is far more than that, of course, to use a good cache, the principle of caching in Jee, the use of the scope, the application of the scene and so on need to have a more profound understanding, so as to use a good 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.