EHCache the use of Web projects

Source: Internet
Author: User

EHCache is a pure Java in-process cache that has the following features: Fast, simple, Hibernate2.1 as pluggable cache, minimal dependencies, comprehensive documentation and testing. Official website http://ehcache.sourceforge.net/

There is no doubt that almost all of the homepage of the site is the highest access, and the data source on the home page is very extensive, most from different objects, and possibly from different db, so to cache the home page is a good idea, then the home page cache strategy is what it looks like, I think it should be a fixed time, for example, 2 minutes to update. So where does this cache go, let's take a look at the assumption that the structure of your application is page-filter-action-service-dao-db, the process of- Places are can do cache, according to the characteristics of the page cache, the page should be cached 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 to request, go to the filter This request is over, no need to go back to the action-service-dao-db. The benefits are reduced server pressure and faster response times for customer segment pages.

So let's take a look at how to do this with Ehcache.

Before using the Ehcache page cache, we have to understand several concepts of ehcache,

1 timetoidleseconds, for how long does not access the cache, then Ehcache clears the cache.

2 Timetoliveseconds, the lifetime of the cache, starting from the time it was created.

Home Page Cache Survival time, we set is 2 minutes, timetoliveseconds should be set to 120, while our timetoidleseconds preferably also set to 2 minutes, or less than 2 minutes. Let's take a look at the following configuration, This configuration fragment should be placed in the Ehcache.xml:

<cache name= "Simplepagecachingfilter"

Maxelementsinmemory = "10"

Maxelementsondisk = "10"

Eternal = "false"

Overflowtodisk = "true"

DISKSPOOLBUFFERSIZEMB = "20"

Timetoidleseconds = "10"

Timetoliveseconds = "10"

Memorystoreevictionpolicy = "LFU"

/>

Simplepagecachingfilter is the name of the cache, maxelementsinmemory indicates that the maximum number of elements in the Simplepagecachingfilter cache in memory is ten, Maxelementsondisk is the maximum number of persisted elements of the cache to the hard disk, and eternal=false means that the cache will die. Overflowtodisk=true means that when the number of elements in the cache exceeds the limit, the elements are persisted to the hard disk, If Overflowtodisk is false, then the Maxelementsondisk setting is meaningless. Memorystoreevictionpolicy=lfu is the cache hit value to clear, that is, after the cache is full, When a new object needs to be cached, the object with the lowest hit value in the cache will be cleared out of the cache, freeing up the new object (the article concludes with an introduction to the 3 cache emptying policies in Ehcache).

Configuration of the 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 so many steps, we can do a cache for a page, put the above configuration in your Web. XML, then when you open the homepage, you will find that 2 minutes before a bunch of SQL statements appear on the console. Of course you can also adjust to 5 minutes, in short, everything is under control.

OK, caching the entire page looks very simple, even do not need to write a line of code, just a few lines of configuration on the line, simple enough, although it seems simple, but the fact that the internal implementation is not simple oh, interested, you can see Simplepagecachingfilter The source code of the inheritance system.

The above configuration is for the cache of all the first page, if you want to cache only part of the first page, you need to use simplepagefragmentcachingfilter this filter. Let's take a look at the following snippet:

<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 cache of the local page is done. It seems that there is no oscache tag.

In fact, there is a feature in Cachefilter, that is, gzip, that is, the elements in the cache is compressed, if the customer browser support compression, filter will directly return the compressed stream, which saves bandwidth, the decompression work to the customer's browser, If the customer's browser does not support gzip, then filter will take the cached elements out of the decompression and then back to the client browser (most crawlers do not support gzip, so filter will be decompressed and then return to the stream), the advantage is to save bandwidth, the disadvantage is to increase the burden on the customer's browser ( But I think the burden is minimal for modern computers.

Well, if your page just needs to use the page cache, can not think about Ehcache, because it is very simple, and easy to use.

Summary: Ehcache is a very lightweight cache implementation, and since 1.2 support the cluster, the current version is 1.3, and Hibernate is the default cache provider. Although this article is about Ehcache support for page caching, But Ehcache's function is much more than that, of course, to use a good cache, the principle of the cache in Jee, the scope of use, the application of scenarios and so on need to have a more profound understanding, so as to use good cache, with the cache.

3 purge policies cached in Ehcache:

1 FIFO, first in firstly out, this one is the most familiar, FIFO, not much to say

2 LFU, less frequently used, is the strategy used in the above example, and it is straightforward to say that it has been used at least. As mentioned above, the cached element has a hit attribute, and the least hits value will be cleared out of the cache.

2 LRU, Least Recently used, the least recently used, the cached element has a timestamp, and when the cache is full, and you need to make room to cache the new element, the element in the existing cache element that has the longest timestamp from the current time is cleared out of the cache.

Brief introduction

Ehcache cache mechanism in both:

· Memorystore (Memory storage)

· Diskstore (disk storage)

Memorystore

Memorystore is always available, but cannot be manipulated directly, and all caches are stored.

· The appropriate element type

All the element can be placed in the Memorystore.

· Security: Use multiple threads to check for memory leaks in parallel.

· JDK: Use JDK1.5 's linkedhashmap to store elemen.t

· Fast: is the fastest caching mechanism because it is stored in memory.

· Failure Strategy (Memory)

The cache can configure the maximum number of cached element and the expiration time. If you add elemtent, the number of element in the cache reaches the maximum number of caches and the Overflowtodisk configured property is true. Ehcache will be more configurable memorystoreevictionpolicy the expiration policy to output the element to disk. If Overflowtodisk is Fasle, Ehcache will remove in-memory Element.ehcache supports three failure policies: Lru,lfu,fifo.

It is important to note that the failed element in the cache is not cleaned out immediately, so the method Calculateinmemorysize () method should be called to get the true size of the memory.

Diskstore

The diskstore can be cached on an external device (hard disk).

· Diskstores is Optional

Ehcache supports Diskstore from version 1.5. If you need multiple diskstore, it's best to configure them with different file paths.

· Turn off the disk cache: simply comment out the disk cache configuration entry in the Ehcache.xml configuration file. The Ehcache-failsafe.xml disk cache configuration does not affect your own cache.

· The appropriate element type

It is important to note that in order to use disk caching, the cached element must implement a serialized interface. Otherwise, a Notserializableexception exception will be thrown.

· Storage: Ehcache creates a cache_name.data file under the file path for each cache configuration, and a cache Name.index file is generated if the disk persistence technology is used.

· Failure

Ehcache has a background thread dedicated to ellment failure monitoring and cleanup. Set the thread run interval, which can be done by setting the Diskexpirythreadintervalseconds property, which should not be set too low. Doing so causes the cleanup thread to consume a large amount of CPU resources. The default value is 120 seconds.

· Persistence of

Persistence can be configured in the Diskpersistent configuration item of element, if configured as "false" or "omitted" after CacheManager shutdown or startup, The files used to cache the element will be erased. If set to "true", the data and index files are saved and are available for the newly created CacheManager element.

The call cache must be displayed when used. Flush () will not cache the data to disk.

Disk cache steps: The element will be serialized to the index file by flushing the non-invalidated element from Memorystore to Diskstore,element being written to the data file.

Ehcache Cache Recycling Policy

Cache recycling is when the cache is full, Ehcache cleans up the cache based on the specified policy. The cache recycling policy here is different from the fail-clean policy in ehcache. The fail-clean policy is the strategy used to batch clean up the failed element, Eventually all the failed element will be cleaned up, but the order of cleanup is different. The maximum number of element caches in Ehcache is specified by Maxelementsinmemory. When the number of element in the cache reaches the value specified by Maxelementsinmemory, Ehcache cleans up the cache based on the specific policy. The default policy is LRU (least recently used).

The disk cache size is not limited by default, but can be specified by Maxelementsondisk. When the disk cache reaches the value specified by Maxelementsondisk, Ehcache cleans up the cache on the disk by using the default policy of LFU (the least frequently used).

Make sure is using a supported Java version.
Place the Ehcache jar into your classpath.
Ensure the libraries required to satisfy dependencies is also in the classpath.
Configure Ehcache.xml and place it in your classpath.
Optionally, configure an appropriate logging.



Xxxx




downloads:http://sourceforge.net/projects/ehcache/files/

Welcome to ehcache:http://ehcache.org/


EHCache the use of Web projects

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.