HTTP Caching
HTTP 缓存可以显著提高 Web 应用程序的性能。HTTP 缓存围绕`Cache-Control`响应头和后续条件请求头旋转,例如`Last-Modified`和`ETag`。Cache-Control`指示私有(例如浏览器)和公共(例如代理)缓存如何缓存和重复使用响应。`ETag`头用于发出条件请求,如果内容没有更改,则可能导致 304(NOT_MODIFIED,没有正文)。`ETag
可以看作是 Last-Modified
头的更高级的继承者。
HTTP caching can significantly improve the performance of a web application. HTTP caching
revolves around the Cache-Control
response header and subsequent conditional request
headers, such as Last-Modified
and ETag
. Cache-Control
advises private (for example, browser)
and public (for example, proxy) caches how to cache and re-use responses. An ETag
header is used
to make a conditional request that may result in a 304 (NOT_MODIFIED) without a body,
if the content has not changed. ETag
can be seen as a more sophisticated successor to
the Last-Modified
header.
本节介绍 Spring WebFlux 中可用的与 HTTP 缓存相关的选项。
This section describes the HTTP caching related options available in Spring WebFlux.
CacheControl
CacheControl
提供对与 Cache-Control
头部相关的设置的支持,并且被当作参数接受在多个位置:
CacheControl
provides support for
configuring settings related to the Cache-Control
header and is accepted as an argument
in a number of places:
尽管https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.2[RFC 7234]描述了`Cache-Control`响应标头的所有可能的指令,但`CacheControl`类型采用了面向用例的方法,重点在于常见的场景,如下图所示:
While RFC 7234 describes all possible
directives for the Cache-Control
response header, the CacheControl
type takes a
use case-oriented approach that focuses on the common scenarios, as the following example shows:
-
Java
-
Kotlin
// Cache for an hour - "Cache-Control: max-age=3600"
CacheControl ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS);
// Prevent caching - "Cache-Control: no-store"
CacheControl ccNoStore = CacheControl.noStore();
// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
CacheControl ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic();
// Cache for an hour - "Cache-Control: max-age=3600"
val ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS)
// Prevent caching - "Cache-Control: no-store"
val ccNoStore = CacheControl.noStore()
// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
val ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic()
Controllers
控制器可以为 HTTP 缓存添加显式支持。我们建议这样做,因为在与条件请求头比较资源的`lastModified`或`ETag`值之前需要计算该值。控制器可以向`ResponseEntity`添加`ETag`和`Cache-Control`设置,如下面的示例所示:
Controllers can add explicit support for HTTP caching. We recommend doing so, since the
lastModified
or ETag
value for a resource needs to be calculated before it can be compared
against conditional request headers. A controller can add an ETag
and Cache-Control
settings to a ResponseEntity
, as the following example shows:
-
Java
-
Kotlin
@GetMapping("/book/{id}")
public ResponseEntity<Book> showBook(@PathVariable Long id) {
Book book = findBook(id);
String version = book.getVersion();
return ResponseEntity
.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.eTag(version) // lastModified is also available
.body(book);
}
@GetMapping("/book/{id}")
fun showBook(@PathVariable id: Long): ResponseEntity<Book> {
val book = findBook(id)
val version = book.getVersion()
return ResponseEntity
.ok()
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.eTag(version) // lastModified is also available
.body(book)
}
前面的示例以空正文发送 304 (NOT_MODIFIED) 响应,如果与条件请求头的比较表明内容没有更改。否则,`ETag`和`Cache-Control`将会被添加到响应。
The preceding example sends a 304 (NOT_MODIFIED) response with an empty body if the comparison
to the conditional request headers indicates the content has not changed. Otherwise, the
ETag
and Cache-Control
headers are added to the response.
也可以在控制器中对条件请求标头进行检查,如下例所示:
You can also make the check against conditional request headers in the controller, as the following example shows:
- Java
-
@RequestMapping public String myHandleMethod(ServerWebExchange exchange, Model model) { long eTag = ... (1) if (exchange.checkNotModified(eTag)) { return null; (2) } model.addAttribute(...); (3) return "myViewName"; }
1 | Application-specific calculation. |
2 | Response has been set to 304 (NOT_MODIFIED). No further processing. |
3 | Continue with request processing.
|
4 | Application-specific calculation. |
5 | Response has been set to 304 (NOT_MODIFIED). No further processing. |
6 | Continue with request processing. |
有针对`eTag`值、lastModified`值或两者检查条件请求的三个变体。对于条件`GET`和`HEAD`请求,你可以将响应设置为 304 (NOT_MODIFIED)。对于条件`POST
、PUT`和`DELETE
,你可以将响应设置为 412 (PRECONDITION_FAILED) 以防止并发修改。
There are three variants for checking conditional requests against eTag
values, lastModified
values, or both. For conditional GET
and HEAD
requests, you can set the response to
304 (NOT_MODIFIED). For conditional POST
, PUT
, and DELETE
, you can instead set the response
to 412 (PRECONDITION_FAILED) to prevent concurrent modification.
Static Resources
您应该使用 Cache-Control
和条件响应标头提供静态资源以获得最佳性能。请参见有关配置 Static Resources 的部分。
You should serve static resources with a Cache-Control
and conditional response headers
for optimal performance. See the section on configuring Static Resources.