Ehcache implements overall page cache and partial page cache.

Source: Internet
Author: User

Ehcache implements overall page cache and partial page cache.

I have previously written a basic introduction to spring cache and ehcache and implemented cache Management Using annotations. Today I will record the page cache technology of web projects.

 

Is page cache necessary?.

In this case, the homepage of almost all websites has the highest success rate, and the data sources on the homepage are very extensive. Most of them come from different objects and may come from different databases, therefore, it is necessary to cache the homepage. So how should I design the homepage Cache Policy? I think it should remain the same within a fixed period of time, for example, update once every 2 minutes. So where should the cache be implemented? Let's take a look. The current application structure is usually page-filter-action-service-dao-db. In this process,-can be cached, according to the page cache features, the page cache should be as close as possible to the customer, that is, between the page and the filter. This advantage is that after the first user request, the page is cached, when the second user comes back to the request, the request to filter ends, and no action-service-dao-db is required. The benefits are reduced server pressure and accelerated response to customer segments. After learning about this, we will introduce the key points.

Features of ehcache page Cache: The elements in the cache are compressed. If the customer's browser supports compression, the filter will directly return the compressed stream, which saves the bandwidth and gives the decompression work to the customer's browser, if the client's browser does not support gzip, the filter will extract the cached elements and return them to the client's browser. (most crawlers do not support gzip, so the filter will decompress the package and then return back to the back). The advantage of this is to save bandwidth, and the disadvantage is that it increases the burden on the customer's browser.

1. SimplePageCachingFilter

It is a simple implementation of the page cache Filter in the ehcache-web module and is suitable for compressing Http responses (response), such as HTML, XML, and JSON. It uses the static method create created through CacheManager to create the single-instance CacheManager. In this way, if the previous CacheManager instance already exists, it will be used directly, instead of being created. Therefore, ehcache under the root path of the class is usually used by default. xml file to create CacheManager. However, if Ehcache and Spring are integrated in our project and the Ehcache configuration file specified in the Spring configuration file is not the default location, spring will use the specified configuration file to initialize CacheManager first, so that CacheManager will not be initialized in SimplePageCachingFilter, but will be initialized directly using Spring. The key used by the page cache is obtained through the calculateKey () method of SimplePageCachingFilter.The internal logic is the URI of the request.And the following query string as the keyReturns, Such as "/user/index. jsp? Name = abc ", which makes it widely used. It does not depend on the host name and port number, which makes it suitable for requests with multiple domains or ports with the same content. If necessary, we can rewrite the calculateKey method to implement our own key computing logic. This is necessary because AJAX is used on many pages of the project. To ensure that the JS request data is not cached by the browser, each request may be a different number of parameters. If SimplePageCachingFilter is used, the keys generated each time are different, and 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 applicable to caching the entire page. If you only need to cache a specific segment, such as the part included in jsp: include, you need to use SimplePageFragmentCachingFilter.

The first part is the overall page cache.

Step 1: Configure ehcache first. xml specifies the SimplePageCachingFilter cache. the lifecycle of the page cache is 60 seconds, and the timeToIdleSeconds time is 120 seconds. Do not set it too long.

<! -- Cache all pages --> <cache name = "SimplePageCachingFilter" maxElementsInMemory = "10" maxElementsOnDisk = "10" eternal = "false" overflowToDisk = "false" timeToIdleSeconds = "120 "60" memoryStoreEvictionPolicy = "LFU">
</Cache>

Step 2:Add PageCachingFilter to web. xml.

NOTE: If we use ehcache. when the name of the page cache in xml is SimplePageCachingFilter. the cacheName of the page cache filter in xml does not need to be defined, because it is the default. If it is not SimplePageCachingFilter, I must specify cacheName.

Also, the url-pattern should be/pageCacheController/testPageCache. do, instead of/testPageCache. do.

<! -- Ehcache page cache 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 3:Compile 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 have accessed the controller"); return new ModelAndView ("testPageCache", model );}}
<% @ 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"> The above is the testPageCache. jsp page.

Step 4:Access/pageCacheController/testPageCache. do observe the page time and view the console output. During the cache lifecycle, the page is refreshed between 60 seconds. The time on the page will not change, when the cache is accessed, the time changes immediately. See the figure below.

Refresh the page to view the console within 60 seconds. I found that "I am accessing the controller" was not printed out, that is, during the second access during the cache lifecycle, only the rest of page-filter-action-service-dao-db is not accessed. If you have done it yourself, you will be interested in the information printed on the console. Here I will point out an important Cache-control-> max-age = 0, you can study this and I will not talk about it.

Here, a simple example of the overall page cache is completed. Of course, the actual project is definitely more complicated than this, but the truth is the same. As long as you understand the principles, everything is OK!

The second part is partial page cache.

 Let me simply say the same thing as above.

Configure ehcache. xml

<! -- Partial page cache --> <cache name = "inherit" maxElementsInMemory = "10" maxElementsOnDisk = "10" eternal = "false" overflowToDisk = "false" timeToIdleSeconds = "120" timeToLiveSeconds = ""60" memoryStoreEvictionPolicy = "LFU"> </cache>

 

Configure web. xml. Pay attention to the following points. We need to specify the <dispatcher> include </dispatcher> element in the filter for the jsp page of INCLUDE. If no <dispatcher> element is specified, the default value is REQUEST. I have added a new page as the include page.

<! -- Ehcache page partial cache --> <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 are executed in the order below. do not change the order. --> <filter-mapping> <filter-name> PageFragmentCachingFilter </filter-name> <url-pattern>/page/testPageFragmentCache. jsp </url-pattern> <dispatcher> INCLUDE </dispatcher> </filter-mapping>
On the testPageFragmentCache. jsp page, I called the controller method above to observe the time. If you do this step by step according to my practice, You Need To comment out the filter in the overall cache of the page to test the partial cache, which is not required in reality, I used the same access address for laziness.
<% @ 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"> 

To see the console changes

The simple content of the OK page cache is basically finished. please correct me if there is anything unreasonable.

 

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.