REST note (6)-Service with scalability and fault tolerance of the Cache architecture

Source: Internet
Author: User
Document directory
  •  
  •  
  • Cache channel)

Let's look back at the simple implementation of cache in rest wcf 4.0:

1. Configuration

<Caching>

<OutputCacheSettings>
<OutputCacheProfiles>
<Add duration = "20" name = "outCache" varyByParam = "none"/>
</OutputCacheProfiles>
</OutputCacheSettings>

2. Use Configuration

[OperationContract]

[WebGet (UriTemplate = "/Time")]
[AspNetCacheProfile ("outCache")]
Public DateTime GetTime ()
{
Return DateTime. Now;

}

Test the Request with Fiddler: On the Request Builder tab, select the Get method, enter the test address, and click the HTTP Response Header obtained by executing the command, for example:

(Figure 1)

Note: There are two HTTP headers in the red underline Department: Cache-Control and Expires. This is the Cache information in the HTTP protocol.

The two important header information, leave a suspense first, will be discussed later.

Caching is an important way to obtain information on the Web. It is implemented through HTTP secure and idempotent GET operations.

In the REST architecture, due to the stateless interaction between the server and the client (Note: The stateless mentioned in REST refers to

Stateless. One of the key principles of Web architecture is that servers and services should not maintain the application status.

).

In this way, a problem occurs. To identify the client, each time the client wants to obtain resources through the service,

The application status information must be exchanged, which may cause performance loss. Fortunately, in the REST architecture, we can also

The cache greatly improves the service throughput to a certain extent. But the disadvantages are also obvious: the client obtains

No one can guarantee synchronization with the server. This is the weak consistency of the cache (weak consistency ).

The expression of a resource is valid only for a period of time. This period is the retention period of the resource. One

The expired resource expression must be verified by the server before it can be used.

 

Cache type

According to the deployment method, the cache is divided into local cache and shared cache. The shared cache includes proxy cache and

Reverse proxy cache ).

  • Local cache (also called client cache) after obtaining the resource expression, the client caches the resource in the local disk or memory through the browser.

In this way, you can directly obtain these resources from the local machine the next time you access these resources.

Advantage: avoids network transmission and provides the fastest speed.

Disadvantage: because it is only cached locally on the client, it can only be obtained from the server when there are other client requests.

  • The proxy is cached between the server and the client, and a server shared by both parties is deployed to cache data. This is the proxy cache. It can be inside or outside the enterprise firewall.

Advantage: all clients that can obtain resources through the Proxy Cache Server can share the resource expression in the cache.

Disadvantage: additional deployment facilities are added.

  • Reverse proxy cache. The reverse proxy, also known as the web Service accelerator, is located at the front end of the Web server and serves as the content cache server of the Web server.

It targets web servers rather than browser users, so it becomes a reverse proxy, usually located in front of the Web server. It is based on

The HTTP header information returned by the Web source server is used to cache the information. Common reverse proxy implementations include Squid.

  Cached HTTP Response Header Information

 

There are two main types of HTTP response header information used to Control cache behavior: Expires, Cached-Control. This returns the HTTP response.

Information. So what are the effects of these two commands on the cache?

  • Expires

Expires is used to control the absolute expiration time of the cache expression. After the expiration time, the expression becomes invalid. client requests must be sent to the server, and the service

End to re-calculate and send the corresponding response. If the Expires value is equal to the Date value or Expires = 0, it indicates that it Expires immediately. If you want

If it is set to never expire, the service can set Expires to one year.

  • Cached-Control

Unlike Expires, Cached-Control can be used to Control cache behavior in requests and responses. The value can be composed of multiple commands.

Instructions are separated by semicolons. These commands determine the cache location and the cache duration.

Conclusion: If we can determine the expiration time, we can use Expires. If you specify how long the cache will take after it leaves the source server

If appropriate, use the max-age or s-maxage of Cached-Control (max-age and s-maxage are measured in seconds ). For cacheable

The server is recommended to include ETag and Last-Modified information in the HTTP header of the response. (If you are not familiar with ETag, see

In the previous section ).

If the client wants to verify whether the Cached statement has expired on the server, you can use

No-cache command.

The other two important HTTP headers in the cache are Last-Modified and Date. The former indicates the last modification time of the resource, and the latter indicates the generation time.

Cached-Control: in the HTTP protocol specification, the cache is controlled by standardizing the Cached-Control command.

Cached-Control commands

  • Max-age: can be used in a request or response.

In response, cache and freshness can be controlled at the same time. It enables the local cache and shared cache (proxy cache and reverse proxy cache) to cache a representation.

Is determined by its value. The Unit is seconds. Its value will overwrite the value in Expires. Response example:

Cached-Control: max-age = 20 (for example, Cached-ontrol: private (for example)

In the request, the client can accept the cached expression generated not earlier than the max-age value. If the client specifies max-age = 0, the request

The cache will be sent to the source server for verification, so as to obtain the latest statement. That is to say, the value of max-age is the current request time of the client.

Compared with the time when resources are generated on the source server. That is, the current time-the time when cache resources are generated on the source server.

  • No-cache: it can be used in a request or response.

In the response, each cache is required to be verified on the server. It takes effect only when the expression is cached. When there is no cache,

Is it true that all clients get the expression of resources obtained by the server. Response example: Cached-Control: no-cache

In the request, it uses the same max-age = 0, and the client obtains the latest resource expression. Unlike max-age = 0,

No-cache updates all cached statements in the intermediate proxy to the latest one, while the intermediate proxy in max-age = 0

Cache can be used again

  • No-store: it can be used in a request or response.

In the response, the expressions that can be cached are not cached. Response example: Cached-Control: no-store

In the request, the resource is required not to be cached and all obtained are the latest expressions.

  • S-maxage: Used in response.

It is the same as max-age. But it can only be done by the shared cache (proxy cache and reverse proxy cache), and cannot use local cache. Response example:

Cached-Control: s-maxage = 20 distinguishes s-maxage from max-age. The former has s, meaning share ).

  • Public: Used in the response. Make the local cache or shared cache (proxy cache and reverse proxy cache) cache a response, but it is not like s-

Maxage specifies an insurance period. The public priority is higher than the Authorization header information. Generally, if the HTTP response contains

Authorization, so the expression will not be cached; but if it contains pulic header information at the same time, the expression will certainly be cached.

If the client needs to be authenticated as a valid client when obtaining the resource expression, be cautious when using public. Because the cache server does not

Concerned about client verification. response example: Cached-Control: public

  • Private: Used in the response. Enable the expression to be cached and only use the local cache, which is implemented on the client. Similarly, it does not specify freshness.
It prevents the shared cache (proxy cache and reverse proxy cache) from caching the expressions that can be cached. Response example: Cached-ontrol: private (for example, 1)
  • Must-revalidate: Used in the response. It usually caches the expressions that can be cached, but the client will

The cached information is sent to the server for verification. The statement is available only when verification is successful. For client requests, the cache will also be

It is a relatively efficient operation than directly obtaining resources from the server, because it prevents

The service logic of the server is repeatedly called as the request of the client. Response example: Cached-Control: must-revalidate

  • Proxy-revalidate: Used in the response. It is the same as must-revalidate, but is only used in the shared proxy cache. Response
For example, Cached-Control: proxy-revalidate
  • Max-stale: Used in the request. Usage: max-stale = 36. The client can accept the expressions within the expiration range specified by max-stale.

If the client ignores this value, it can accept any expired expression.

  • Min-fresh: Used in the request. Usage: min-fresh = 36. The client can accept the resource generation time plus the value specified by min-fresh.

The latest cached statement.

  • Only-if-cached: Used in the request. The client only returns the cached expression. If the latest expression of the resource does not exist in the cache, the Code 504 is returned.

Two new commands:

  • Stale-while-revalidate: Used in the response. It enables the cache to send the cache to the server for verification when responding to the client.

(Sent to the server in asynchronous non-blocking mode for verification ). It allows the cache to leave the response to the client even if the response has expired.

Therefore, it responds to the client at the cost of consistency, reducing latency. After the specified time (in seconds) expires, if the server

If the statement verification is not completed, the cache will be discarded. Response example: stale-while-revalidate = 20

  • Stale-if-error: Used in the response. It allows the client to return

Description that may expire. REST in Practice: if the cached statement exceeds the time range specified by stale-if-error

Storage should not be responded to the client. The unit of stale-if-error value is second. Its response format is Cache-Control: stale-if-error = 20.

In my understanding, if a cached statement contains the following response headers:

Therefore, this statement should not be returned to the client 20 seconds after the specified time of Date, that is, 27 Dec 2011 09:24:50 GMT.

There are two other commands used to implement the cache channel. We will introduce them below.

Cache channel)

It is a technology that extends the retention period of cached resources. The cache of the resource Response Header (that is, the cache Channel Protocol) cannot be parsed during the retention period.

After the expiration, the Cache Server becomes invalid. the cache of the resource response header still regards the resource as the latest resource after it expires, and the cache server receives an expiration notification.

When the client uses the no-cache command to send a request, the cache can be updated by forcibly requesting resources to be verified on the server.

The Cache channel uses two Cache-Control commands:

  • Channel: it provides the absolute URI path for channel Expansion. Cache can subscribe to this URI to get a cache-related event notification
  • Group: the extension provides a relative URI that can be used to group multiple caches.

After you specify the cache expiration time through max-age = 600 and receive the client request again, the cache must be verified and obtained from the source server.

However, when the following conditions are met, if you can understand the cache channel protocol in the path sent back to the client, both the channel and the group cache will

Can be extended.

1. the cache is continuously polling, and the frequency is at least lower than the interval defined by the channel.

2. No expired information is sent from any channel associated with the cached URI or the cached URI of the group.

Example:

Precision defines the precision specified by the channel. That is to say, the cache must poll the channel at least once within 15 seconds to extend the association with this channel.

The retention period of All cached expressions.

Lifecycle: specifies that the events in this feed are available within at least one hour after release.

Precision and lifecycle are not attributes supported by the SyndicationFeed object in FCL, but extended attributes. This also complies with the cache channel:

Can understand the purpose of caching.

The code for implementing the preceding feed is as follows:

SyndicationFeed = new SyndicationFeed {Title = new TextSyndicationContent ("feed Tile"), LastUpdatedTime = new DateTimeOffset (DateTime. now), Description = new TextSyndicationContent ("feed Description Content")}; feed. authors. add (new SyndicationPerson ("aa@gmial.com", "zhanshan", "cnblogs.com"); feed. language = "us-en"; feed. generator = "test feed"; feed. links. add (new SyndicationLink (new Uri ("http://www.cnblogs.com/tyb1222"), "via", "linkTitle", "application/Atom + xml", 1000); feed. categories. add (new SyndicationCategory ("blog"); feed. contributors. add (new SyndicationPerson ("aa@gmial.com", "zhanshan", "cnblogs.com"); feed. elementExtensions. add (new SyndicationElementExtension ("permission"," http://tyb1222.cnblogs.com ", 900); feed. elementExtensions. add (new SyndicationElementExtension ("lifecycle", "http://tyb1222.cnblogs.com", 3600); return feed; if the feed contains an expired event item, its link Control associates it with the ID of the group to which the resource expression belongs (that is, the group specified in Cache-Control

). The value of href can be used to associate resources in this group. After receiving the feed, the cache stops extending the cache retention period of the group of resources.

When a Get request gets a resource, the cache goes back to the server to verify the expiration expression. For the abstract that contains expired event items:

Only the Update attribute of the SyndicationItem example is set for the event item with the expected entry that has expired. The Code is as follows:

SyndicationItem item1 = new SyndicationItem("Title1",                                            "Microsoft may have patents, patent applications, trademarks, ...more",new Uri("36",UriKind.Relative))                        {Summary = new TextSyndicationContent("sumary"), LastUpdatedTime = DateTime.Now};

Of course, the implementation of the cache channel technology does not need to be implemented using Atom. Here we just use it as an example. If you are not clear about the Atom protocol, refer to here

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.