Ehcache page overall cache and local cache

Source: Internet
Author: User

is the page cache necessary?

In this case, almost all of the site's homepage is the highest access rate, and the home page of the data source is very extensive, most from different objects, and may come from different db, so to the home page cache is very necessary. So how should the caching strategy of the home page be designed? I think it should be fixed within a certain time, say, 2 minutes update. So where is this cache supposed to be? Let's take a look at the current structure of our application is generally page-filter-action-service-dao-db, the process of-the place is can do cache place, according to the characteristics of the page cache, the page should be cached as close to the customer's place, is between the page and filter, the advantage is that after the first user request, the page is cached, the second user to request the time, 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. Having learned this, we begin to introduce the key.

Ehcache Page Cache Features: The element in the cache is compressed, if the customer browser supports compression, filter will return the compressed stream directly, thus saving bandwidth, the decompression work to the customer's browser, if the customer's browser does not support gzip, then filter The cached elements will be extracted and then returned 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 of the customer's browser

1. Simplepagecachingfilter

It ehcache-web a simple implementation of the page cache filter under the module, suitable for the HTTP response (response) that can be compressed, such as HTML, XML, JSON, and so on. It will use the singleton CacheManager created by the static method of CacheManager, so that if an instance of CacheManager is already present, it will be used directly and will not be created. The Ehcache.xml file under the classpath is typically used to create CacheManager, but if Ehcache and spring are consolidated in our project and the Ehcache profile specified in the spring configuration file is not the default location, Spring uses The specified profile takes precedence over initialization of CacheManager, so that the simplepagecachingfilter is not initialized when CacheManager is used, but instead is initialized directly using spring. The key used by the page cache is obtained through the Simplepagecachingfilter Calculatekey () method. Its internal logic is to get the request when the URI and subsequent query string as key to return, such as "/USER/INDEX.JSP?NAME=ABC", which makes it a very wide range of applications. It does not depend on the host name and port number, which makes it equally suitable for situations where multiple domains or multiple ports request the same content. If necessary, we can rewrite the Calculatekey method to implement our own logic of computing key. This is necessary, because in the project many pages use Ajax, in order to ensure that the JS request data is not cached by the browser, each request may be a different number of parameters. If you use Simplepagecachingfilter, each time you generate a different key, the cache is meaningless. In this case, we will overwrite the Calculatekey () method.

2. Simplecachingheaderspagecachingfilter provides HTTP cache header information, which is rarely used.

3. Simplepagefragmentcachingfilter

Simplepagecachingfilter is suitable for caching the entire page, if you only need to cache a fragment, such as using the jsp:include included, this time you need to use Simplepagefragmentcachingfilter.

The first part is the overall page cache

First step: Configure Ehcache.xml to specify our Simplepagecachingfilter cache, here Specify the page cache life cycle is 60 seconds, there is timetoidleseconds time love you is 120 seconds, Here's to be careful not to set too long

   <!--page All cache-   <cache name= "Simplepagecachingfilter"           maxelementsinmemory= "ten"               maxelementsondisk= "                 eternal=" false "           overflowtodisk=" false "           timetoidleseconds="           timetoliveseconds= "memorystoreevictionpolicy=" "           LFU" >
</cache>

Step Two: Add the page cache filter Pagecachingfilter in Web. Xml.

Attention: If we name the page cache named Simplepagecachingfilter in Ehcache.xml, we re-cachename the page cache filter in Web. XML is not defined because it is the default, if not SIMPLEPAGECACHINGFI Lter, this is what I have to specify CacheName.

A little bit of Url-pattern's designation should be/pagecachecontroller/testpagecache.do, not/testpagecache.do.

    <!--Ehcache Page Cache Filter--    <filter>        <filter-name>PageCachingFilter</filter-name>        <filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>        <init-param>              <param-name>cacheName</param-name>              <param-value> simplepagecachingfilter</param-value>         </init-param>      </filter>       <filter-mapping >        <filter-name>PageCachingFilter</filter-name>        <url-pattern>/ Pagecachecontroller/testpagecache.do</url-pattern>    </filter-mapping>

Step three: Write the Controller test class

@Controller @requestmapping ("Pagecachecontroller") public class Pagecachecontroller {    private final static Logger Log = Logger.getlogger (Pagecachecontroller.class);        @RequestMapping ("Testpagecache") public    Modelandview Testpagecache () {        Modelmap model = new Modelmap ();        Date date = new Date ();        Model.addattribute ("Date", date.tolocalestring ());        Log.info ("I came to visit the controller");        return new Modelandview ("Testpagecache", model);}    }
View Code

Above this is the testpagecache.jsp page

Fourth step: Visit/pagecachecontroller/ Testpagecache.do observe the page time and view the console output, refresh the page within the lifetime of the cache, that is, 60 seconds, the time on the page will not change, and when the lifetime of the cache is accessed, the time changes immediately. Here's a look at the picture.

Refresh the page within 60 seconds to view the console. Found "I came to the controller" did not print out, that is, in the cache lifetime of our second visit, only through the page-filter-action-service-dao-db in the rest of the page-filter are not accessed. If you have done it yourself, you will be interested in the information that is printed on the console, and I would like to point out an important cache-control-> max-age=0, which you can study, I will not say.

Here is a simple example of the overall caching of pages, but certainly the actual project is more complicated than this, but the truth is the same. As long as you understand the principles, then everything ok!

The second part is the page local cache

The truth is the same as above, and I'll just say it.

Configure Ehcache.xml

  <!--page Local Cache-   <cache name= "Simplepagefragmentcachingfilter"           maxelementsinmemory= "ten"               maxelementsondisk= "                 eternal=" false "           overflowtodisk=" false "           timetoidleseconds="           timetoliveseconds= "memorystoreevictionpolicy=" "           LFU" >    </cache>

Configure Web. XML, here are a few points to note, we INCLUDE the JSP page in the filter to specify <DISPATCHER>INCLUDE</DISPATCHER>, if not specified any < Dispatcher > element, the default value is that request will not intercept. I have a new page that adds a page as an include

<!--ehcache page local Cache--    <filter>        <filter-name>pagefragmentcachingfilter</filter-name >        <filter-class>net.sf.ehcache.constructs.web.filter.simplepagefragmentcachingfilter</ filter-class>        <init-param>              <param-name>cacheName</param-name>              <param-value >SimplePageFragmentCachingFilter</param-value>         </init-param>      </filter>       <!- -This is a filter chain. They is executed in the order below. Don't change the order. -    <filter-mapping>        <filter-name>PageFragmentCachingFilter</filter-name>        <url-pattern>/page/testPageFragmentCache.jsp</url-pattern>        <dispatcher>include</ Dispatcher>    </filter-mapping>
Testpagefragmentcache.jsp page, for convenience I still call the controller method above to observe the time. If you are following my steps, to test the local cache, you need to comment out the overall page cache filter, actually do not need, but I used the same access address for lazy
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

See below

Refresh the page, no changes the page of our include is cached

To see how the console changes.

Ehcache page overall cache and local 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.