HTTP 缓存
HTTP 缓存可以显著提高 Web 应用程序的性能。HTTP 缓存围绕着 Cache-Control 响应头,以及随后的条件请求头(例如 Last-Modified 和 ETag)。Cache-Control 告知私有(例如,浏览器)和公共(例如,代理)缓存如何缓存和重用响应。ETag 头用于发出条件请求,如果内容未更改,可能会导致 304 (NOT_MODIFIED) 且没有正文。ETag 可以看作是 Last-Modified 头更复杂的继任者。
本节描述了 Spring Web MVC 中可用的 HTTP 缓存相关选项。
CacheControl
CacheControl 为配置与 Cache-Control 头相关的设置提供了支持,并在多个地方接受作为参数。
尽管 RFC 7234 描述了 Cache-Control 响应头的所有可能指令,但 CacheControl 类型采取了一种以用例为导向的方法,侧重于常见场景。
-
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()
WebContentGenerator 也接受一个更简单的 cachePeriod 属性(以秒为单位定义),其工作方式如下:
-
值为
-1不生成Cache-Control响应头。 -
值为
0通过使用'Cache-Control: no-store'指令阻止缓存。 -
值为
n > 0通过使用'Cache-Control: max-age=n'指令将给定响应缓存n秒。
控制器
控制器可以添加对 HTTP 缓存的显式支持。我们建议这样做,因为资源的 lastModified 或 ETag 值需要在与条件请求头进行比较之前进行计算。控制器可以向 ResponseEntity 添加 ETag 头和 Cache-Control 设置,如下例所示:
-
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 头将添加到响应中。
您也可以在控制器中进行条件请求头检查,如下例所示:
-
Java
-
Kotlin
@RequestMapping
public String myHandleMethod(WebRequest request, Model model) {
long eTag = ... (1)
if (request.checkNotModified(eTag)) {
return null; (2)
}
model.addAttribute(...); (3)
return "myViewName";
}
| 1 | 应用程序特定计算。 |
| 2 | 响应已设置为 304 (NOT_MODIFIED) — 无需进一步处理。 |
| 3 | 继续请求处理。 |
@RequestMapping
fun myHandleMethod(request: WebRequest, model: Model): String? {
val eTag: Long = ... (1)
if (request.checkNotModified(eTag)) {
return null (2)
}
model[...] = ... (3)
return "myViewName"
}
| 1 | 应用程序特定计算。 |
| 2 | 响应已设置为 304 (NOT_MODIFIED) — 无需进一步处理。 |
| 3 | 继续请求处理。 |
有三种检查条件请求的方式:针对 eTag 值、lastModified 值或两者。对于条件 GET 和 HEAD 请求,您可以将响应设置为 304 (NOT_MODIFIED)。对于条件 POST、PUT 和 DELETE,您可以将响应设置为 412 (PRECONDITION_FAILED),以防止并发修改。
静态资源
您应该使用 Cache-Control 和条件响应头来提供静态资源,以获得最佳性能。请参阅配置静态资源一节。
ETag 过滤器
您可以使用 ShallowEtagHeaderFilter 添加从响应内容计算的“浅层” eTag 值,从而节省带宽而不是 CPU 时间。请参阅浅层 ETag。