HTTP cache
DiffThis article is derived from BOOK and is different from the official existing documents. This article explains it in more depth and detail in some places. Therefore, we did not force synchronization with the official.
The natural attribute of rich web applications is that they are dynamic. No matter how efficient your program is, each request will always bear a far greater overhead than static files.
And more web programs have not been greatly affected. Symfony is lightning fast, and unless you're doing something super heavy-duty, every request is restored quickly without putting too much stress on the server.
But your site is growing, and overload may become a problem. Processing of typical requests should only be done once. And that's exactly the goal of cache locking.
Caching on the Shoulders of Giants ¶
The most effective way to improve the performance of a program is to cache the entire output of the page and then ignore the entire subsequent request. Of course, for highly dynamic websites, this may not always be the case. In this chapter, you'll learn how Symfony's caching system works and why it's the best solution.
The Symfony caching system is different because it relies on the simplicity and power of the HTTP cache defined by HTTP specification. Rather than reinventing a caching approach, Symfony emphasizes standards that define basic communications on the web. Once you master the basics of "HTTP validation" and "expiration of cached models", you can already master Symfony's caching system.
The process of learning Symfony caching can be divided into four steps:
gateway cache (gateway cache) , or reverse proxy (reverse proxy), which is a separate layer in front of your program. A reverse proxy caches responses as they are returned by your program; it can also respond to requests with cached responses before the request reaches your program. Symfony provides its own reverse proxy, but any reverse proxy will work.
HTTP cacheHTTP cache headers are used between your program and the client to communicate with gateway caches or other caches. Symfony provides reasonable default configuration and a powerful interface for interacting with cache headers.
HTTPExpiration and validation (expiration and validation), these two models are used to determine whether the cached content is fresh/fresh( Can be reused from cache), or whether stale/stale (should be regenerated by the program)
Edge Side Includes (ESI) , edge-side inclusion allows HTTP cache to be used for independent caching of parts of the page (even nested fragments). With the help of ESI, you can even "cache the entire page for 60 minutes, but the sidebar for only 5 minutes."
Since HTTP cache is not exclusive to Symfony, there are many related articles. If you are not familiar with HTTP caching, I highly recommend reading Things Caches Do by Ryan Tomayko. Another good in-depth article is Mark Nottingham's Cache Tutorial.
Using Gateway Cache ¶
When using HTTP caching, cache is completely separate from your program. It resides between your program and the server that initiates the request. between clients.
The task of caching is to receive client requests, then pass them back to your program, and then push them back to the client. The cache here is the "middleman" in the "request-response" communication process between the program and the browser.
Over time, these caches will store every response that is considered "cacheable" (see HTTP Caching Introduction). If the same resource is requested again, the cache will send the cached response to the client, completely ignoring your application.
This type of cache is the HTTP gateway cache, which exists in programs such as Varnish, Squid and Symfony's reverse proxy mode among agents.
Cache Type ¶
But Gateway cache is not the only cache type. In fact, the HTTP cache headers sent by your program are assumed to be interpreted by up to three ways of caching:
Browser caches : Each browser has its own local cache built in, used when you click "Back", or for images and other assets. The browser cache is a private (private) cache, because the cached resources cannot be used by others;
Proxy caches : Proxy refers to a shared (shared) cache because many people can follow (to use) one person. Usually used by large companies or ISPs to reduce access latency and network traffic.
Gateway caches: Similar to a proxy, it is also a shared cache, but on the server side. Often used by network administrators to make websites easier to upgrade, more reliable, and more performant.
Gateway caches are sometimes referred to as reverse proxy caches, surrogate caches (proxy caches), and even HTTP accelerators.
#When the situation where the cached response contains content for a specific user (such as account information) is discussed, private (private) Caching and Sharing (shared) The importance of caching is increasing day by day.
Every response of the program will experience one or both of the first two cache types. These caches are outside of your (program) control, but obey the HTTP caching instructions set in the response.
Symfony Reverse Proxy ¶
Symfony has a built-in reverse proxy (also called gateway cache) written in PHP. It is not a full-featured reverse proxy cache like Varnish, but it is a good start.
For more details on setting up Varnish, see How to Speed Up My Website with Varnish.
It is easy to turn on the proxy: Symfony programs all have a pre-built cache kernel cache core (AppCache
), which uses the default core (AppKernel
) Pack it. This cache core is a reverse proxy.
Turning on caching is easy, just modify your front controller code. You can also make these changes in app_dev.php
to add a cache for the dev
environment:
// web/app.phpuse Symfony\Component\HttpFoundation\Request; // ...$kernel = new AppKernel('prod', false);$kernel->loadClassCache(); // add (or uncomment) this new line! / 添加下面新行! // wrap the default AppKernel with the AppCache one // 用AppCache打包默认的AppKernel$kernel = new AppCache($kernel); $request = Request::createFromGlobals(); $response = $kernel->handle($request);$response->send(); $kernel->terminate($request, $response);
The cache core above will immediately serve as a reverse A proxy works by caching responses from your application and returning them to the client.
If you are using the framework.http_method_override option to read the HTTP method from the _method
parameter, refer to the link above to adjust it for you degree of need.
The cache core has a special getLog()
method, which returns a string to indicate what happened in the cache layer . In a development environment, you can use it to debug or verify your caching strategy.
##1 | error_log($kernel->getLog()); |
1 | Cache-Control: max-age=600, s-maxage=600 |
Expiration and Validation (Expiration and Validation) ¶
Of course you can use validation and expiration at the same time for the same Response
. Because the advantages of expiration outweigh validation, you can easily benefit from the best of both worlds. That is, using expiration and validation together, you can instruct the cache to serve the cached content, while also checking backwards at certain intervals (expiration) to confirm that the cached content is still valid.
You can also define HTTP cache headers for expiration and validation through annotation. Refer to the FrameworkExtraBundle documentation.
More Response methods ¶
The Response
class provides many methods to deal with caching. Here are a few that are particularly useful:
// Marks the Response stale 标记响应过期$response->expire(); // Force the response to return a proper 304 response with no content // 强制响应返回一个没有内容的恰当的304响应$response->setNotModified();
In addition, most cache-related HTTP headers can be set individually using the setCache()
method:
// Set cache settings in one call$response->setCache(array( 'etag' => $etag, 'last_modified' => $date, 'max_age' => 10, 's_maxage' => 10, 'public' => true, // 'private' => true, ));
Summary ¶
The design idea of Symfony is to follow the industry-recognized standard: HTTP. Caching functionality is no exception. Mastering Symfony's caching system means that you are familiar with the HTTP cache model and can use it efficiently. In other words, you can explore the world of HTTP caching and gateway caches represented by Varnish without relying on Symfony documentation and routines.