Use ETags to reduce Web application bandwidth and load page 1/2 _ PHP Tutorial

Source: Internet
Author: User
Tags md5 hash
Use ETags to reduce Web application bandwidth and load by 12th pages. Recently, the public has been strongly interested in the REST-style application architecture, which indicates that the elegant design of the Web is being noticed. Now, we gradually understand the "3 W Architecture (Introduction to Arc

Recently, the public has been strongly interested in the REST-style application architecture, indicating that the elegant design of the Web has begun to attract attention. Now, we gradually understand the scalability and elasticity inherent in the Architecture of the World Wide Web, and further explore ways to use its paradigm. In this article, we will explore a little-known tool that can be used by Web developers. The unnoticeable "ETag Response Header )", and how to integrate it into dynamic Web applications based on Spring and Hibernate to improve application performance and scalability.

The Spring Framework application we will use is based on petclinic. The downloaded file contains instructions on how to add necessary configurations and source code. you can try it on your own.

What is "ETag "?

The HTTP specification defines ETag as the entity value of the requested variable (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html -- Chapter 14.19 ). In other words, ETag is a token that can be associated with Web resources ). A typical Web resource can be a Web page, but it may also be a JSON or XML document. The server is separately responsible for determining what the mark is and its meaning, and transmitting it to the client in the HTTP response header.

How does ETag help improve performance?

Smart Server developers will use ETags together with the "If-None-Match" header of the GET request, so that the cache of the client (such as the browser) can be used. Because the server generates ETag first, the server can use it later to determine whether the page has been modified. Essentially, the client sends this mark back to the server and requires the server to verify its (client) cache.

The process is as follows:

  1. The client requests A page ().
  2. The server returns to page A and adds an ETag to page.
  3. The client displays the page and caches the page together with ETag.
  4. The customer requests page A again and passes the ETag returned by the server in the last request to the server.
  5. The server checks the ETag and determines that the page has Not been Modified since the last client request. the server returns the response 304 (Not Modified -- Not Modified) and an empty response body.

The rest of this article will show two ways to use ETag in Spring-based Web applications, which use Spring MVC. First, we will use the Servlet 2.3 Filter and the MD5 checksum of the display view (rendered view) to generate the ETag (implemented by a "simple" ETag ). The second method uses a more complex method to track the model used in the view to determine the ETag validity (an "in-depth" ETag implementation ). Although we use Spring MVC, this technology can be applied to any MVC-style Web framework.

Before we proceed, we will emphasize the technologies that are presented here to improve the dynamic generation of page performance. The existing optimization technology should also be considered as part of the overall optimization and application performance characteristics adjustment analysis. (See below ).

Top-down Web cache

This article mainly involves using HTTP cache technology for dynamically generated pages. To improve the performance of Web applications, we should adopt a holistic, top-down approach. For this purpose, it is very important to understand the layers through which HTTP requests pass. the appropriate technologies to be applied depend on the hot spots you are concerned about. For example:

  • Use Apache as the front-end of the Servlet container to process static files such as slices and javascript scripts. you can also use the FileETag command to create the ETag response header.
  • Use optimization techniques for javascript files, such as merging multiple files into one file and compressing spaces.
  • Use GZip and Cache Control headers ).
  • To determine the pain points of your Spring framework application, consider using jamonjavascemonitorinterceptor.
  • Make sure that you fully utilize the cache mechanism of the ORM tool, so objects do not need to be frequently regenerated from the database. It is worthwhile to take the time to determine how to make the query cache work for you.
  • Make sure youMinimize the amount of data obtained in the database, Especially the large list. If each page only requests a small subset of the large list, the data of the large list should be obtained once by a page.
  • Minimize the amount of data put into the HTTP session. In this way, the memory is released, and it will be helpful when the application cluster is deployed.
  • UseDatabase profiling)Tool to check what indexes are used during the query. during the update, the entire table is not locked.

Of course, the best saying of application performance optimization is: two measurements, one cut (measure twice, cut once ). Oh, wait. this is for woodworking! That's right, but it applies here too!

ETag Filter content body

The first method we need to consider is to create a Servlet Filter that generates its ETag mark based on the page ("View" in MVC) content. At first glance, any performance improvement obtained by using this method seems to be contrary to intuition. We still have to generate pages and increase the computing time for generating tags. However, the idea here is to reduce bandwidth usage. In the case of a large response time, such as the distribution of your host and client on both ends of the planet, this is largely beneficial. I have seen an application hosted on a server in the Tokyo office in New York. its response time is 350 ms. As the number of concurrent users increases, this will become a huge bottleneck.

Code

The technology we use to generate a mark is to calculate the MD5 hash value from the page content. This is achieved by creating a package on top of the response. The package uses byte arrays to store the generated content. after processing the filter chain, we use the MD5 hash value of the array to calculate the mark.

The implementation of the doFilter method is as follows.
Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) req;
HttpServletResponse servletResponse = (HttpServletResponse) res;

ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ETagResponseWrapper wrappedResponse = new ETagResponseWrapper (servletResponse, baos );
Chain. doFilter (servletRequest, wrappedResponse );

Byte [] bytes = baos. toByteArray ();

String token = '"' + ETagComputeUtils. getMd5Digest (bytes) + '"';
ServletResponse. setHeader ("ETag", token); // always store the ETag in the header

String previousToken = servletRequest. getHeader ("If-None-Match ");
If (previousToken! = Null & previousToken. equals (token) {// compare previous token with current one
Logger. debug ("ETag match: returning 304 Not Modified ");
ServletResponse. sendError (HttpServletResponse. SC _NOT_MODIFIED );
// Use the same date we sent when we created the ETag the first time through
ServletResponse. setHeader ("Last-Modified", servletRequest. getHeader ("If-Modified-Since "));
} Else {// first time through-set last modified time to now
Calendar cal = Calendar. getInstance ();
Cal. set (Calendar. MILLISECOND, 0 );
Date lastModified = cal. getTime ();
ServletResponse. setDateHeader ("Last-Modified", lastModified. getTime ());

Logger. debug ("Writing body content ");
ServletResponse. setContentLength (bytes. length );
ServletOutputStream sos = servletResponse. getOutputStream ();
Sos. write (bytes );
Sos. flush ();
Sos. close ();
}
}

Recently, the public has been strongly interested in the REST-style application architecture, which indicates that the elegant design of the Web has begun to attract attention. Now, we gradually understand the "3 W Architecture (Arc...

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.