How can I use the client cache to optimize the website?

Source: Internet
Author: User

Introduction

How can you optimize your website when its concurrent access is high and it cannot withstand the pressure?
Most people first want to start from the server CacheProgramFor optimization, many different server cache methods have their own characteristics, such as some projects I have participated in, based on the cache hit rate, the server cache and HTTP compression technologies of COM +/enterprise libiary caching/Windows Services, static files, and other methods have been used, but the client cache is often ignored, even if the server cache allows you to access the page very quickly, but she still needs to rely on the browser to download and output, and when you add the client cache, it will bring you many benefits. because she can cache the most frequently accessed pages on the site to fully improve the web server's throughput (usually calculated based on the number of requests per second) to improve application performance and scalability.
According to an online shopping survey, most people are willing to queue up in the store, but they are not willing to wait for online shopping. According to the websense survey, as many as 70% of netusers say they do not want to read pages for more than 10 seconds. More than 70% of users will cancel the current order because of the slow speed.

Basic knowledge

1) What is "last-modified "? 

When the browser requests a URL for the first time, the server returns 200, and the content is the resource you requested, at the same time, there is a last-modified attribute to mark the last modification time of this file on the service end. The format is similar to this:

Last-modified: Fri, 12 May 2006 18:53:33 GMT

When the client requests this URL for the second time, according to the HTTP protocol, the browser will send the IF-modified-since header to the server, asking if the file has been modified after the time:

If-modified-since: Fri, 12 May 2006 18:53:33 GMT

If the resources on the server are not changed, the HTTP 304 (not changed.) status code is automatically returned and the content is blank, which saves the amount of data transmitted. When the server sideCodeWhen the server is changed or restarted, the resource is re-issued, and the returned result is similar to the first request. This ensures that resources are not repeatedly sent to the client, and that the client can obtain the latest resources when the server changes.

2) What is "etag "?

The HTTP Protocol Specification defines etag as the object Value of the requested variable (See 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 solely responsible for determining what the mark is and its meaning, and transmitting it to the client in the HTTP Response Header. The following is the format returned by the server:

Etag: "50b1c1d4f775c61: df3"

The query update format of the client is as follows:

If-None-Match: W/"50b1c1d4f775c61: df3"

If etag does not change, status 304 is returned and no result is returned, which is the same as last-modified. I personally tested etag mainly for resumable download.

How does last-modified and etags help improve performance?

Smart developers will use the HTTP header of the last-modified and etags requests together, so that the cache of the client (such as the browser) can be used. Because the server first generates the last-modified/etag mark, 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 a last-modified/etag to page.
3. The client displays the page and caches the page together with last-modified/etag.
4. The customer requests page a again and passes the last-modified/etag returned by the server in the last request to the server.
5. The server checks the last-modified or etag and determines that the page has not been modified since the last client request. The server returns the response 304 and an empty response body.

Sample Code

The following example describes how to use the server code to operate the Client Cache:

1 // Default cache seconds
2 Int Secondstime =   100 ;
3
4 // Determine whether the last modification time is within the required time
5 // If the file on the server side has not been modified, the returned status is 304 and the content is blank, which saves the amount of data transmitted. If the files on the server have been modified, the returned results are similar to those in the first request.
6 If (Request. headers [ " If-modified-since " ] ! =   Null   && Timespan. fromticks (datetime. Now. ticks - Datetime. parse (request. headers [ " If-modified-since " ]). Ticks). Seconds < Secondstime)
7 {
8 // Test code. The following date is not output when the browser returns the 304 status.
9 Response. Write (datetime. Now );
10
11 Response. statuscode =   304 ;
12 Response. headers. Add ( " Content-Encoding " , " Gzip " );
13 Response. statusdescription =   " Not modified " ;
14 }
15 Else
16 {
17 // Output Current Time
18 Response. Write (datetime. Now );
19
20 // Set Client Cache status
21 Setclientcaching (response, datetime. Now );
22 }
23
24 # Region Setclientcaching ..
25 ///   <Summary>
26 /// Set Client Cache status
27 ///   </Summary>
28 ///   <Param name = "response"> </param>
29 ///   <Param name = "lastmodified"> </param>
30 Private   Void Setclientcaching (httpresponse response, datetime lastmodified)
31 {
32 Response. cache. setetag (lastmodified. ticks. tostring ());
33 Response. cache. setlastmodified (lastmodified );
34 // Public to specify that the response can be cached by the client and the shared (proxy) cache.
35 Response. cache. setcacheability (httpcacheability. Public );
36 // Is the maximum absolute time that allows a document to exist before it is deemed as obsolete.
37 Response. cache. setmaxage ( New Timespan ( 7 , 0 , 0 , 0 ));
38 // Set cache expiration time from absolute time to adjustable time
39 Response. cache. setslidingexpiration ( True );
40 }
41 # Endregion

If your cache is based on files, such as XML or. ashx in HTTP, you can also use the following file-based client cache:

1 # Region Setfilecaching ..
2 ///   <Summary>
3 /// Set client cache based on file
4 ///   </Summary>
5 ///   <Param name = "FILENAME"> </param>
6 Private   Void Setfilecaching (httpresponse response, String Filename)
7 {
8 Response. addfiledependency (filename );
9 // Set the etag HTTP header Based on the timestamp of the processing program file dependency.
10 Response. cache. setetagfromfiledependencies ();
11 // Set the last-modified HTTP header Based on the timestamp of the processing program file dependency.
12 Response. cache. setlastmodifiedfromfiledependencies ();
13 Response. cache. setcacheability (httpcacheability. Public );
14 Response. cache. setmaxage ( New Timespan ( 7 , 0 , 0 , 0 ));
15 Response. cache. setslidingexpiration ( True );
16 }
17 # Endregion

Shows the effect after use:

The tool used is httpwatchpro running in IE. In Firefox, you can use firebug + yslow for testing.
Yslow is a tool that runs based on firebug. It can analyze why your web page is cached and give a score and a reason for slowness. this tool is developed by Yahoo's R & D team.
Conclusion

We have seen how to use the client cache to reduce bandwidth and computing methods. As described above, if you can properly and reasonably use different caches, they will bring you many benefits. I hope this article will provide you with spiritual food for your current or future Web-based projects and use the last-modified and etag response headers at the underlying level to optimize your project.

References:

301 Implementation of permanent redirection and 302 redirection

Understand the HTTP protocol of ASP. NET and Client Cache

 

How can I use the client cache to optimize the website?

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.