对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

HTTP 缓存

HTTP 缓存可以显著提升 Web 应用程序的性能。HTTP 缓存围绕 Cache-Control 响应头以及后续的条件请求头(例如 Last-ModifiedETag)展开。Cache-Control 用于指导私有缓存(例如浏览器)和公共缓存(例如代理服务器)如何缓存和重用响应。ETag 头用于发起条件请求,如果内容未发生变化,则可能返回不带响应体的 304(NOT_MODIFIED)状态码。ETag 可被视为比 Last-Modified 头更高级的继任者。spring-doc.cadn.net.cn

本节介绍 Spring Web MVC 中可用的与 HTTP 缓存相关的选项。spring-doc.cadn.net.cn

CacheControl

CacheControl 提供支持,用于配置与 Cache-Control 标头相关的设置,并可作为参数在多处接受:spring-doc.cadn.net.cn

尽管 RFC 7234 描述了 Cache-Control 响应头所有可能的指令,但 CacheControl 类型采用了一种以用例为导向的方法,专注于常见场景:spring-doc.cadn.net.cn

// 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 属性(以秒为单位),其工作方式如下:spring-doc.cadn.net.cn

控制器

控制器可以显式支持 HTTP 缓存。我们建议这样做,因为资源的 lastModifiedETag 值需要在与条件请求头进行比较之前进行计算。控制器可以向 ETag 添加 Cache-Control 头部和 ResponseEntity 设置,如下例所示:spring-doc.cadn.net.cn

@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(未修改)响应。否则,ETagCache-Control 头部将被添加到响应中。spring-doc.cadn.net.cn

你也可以在控制器中对条件请求头进行检查,如下例所示:spring-doc.cadn.net.cn

@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(未修改)——无需进一步处理。
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(未修改)——无需进一步处理。
3 继续处理请求。

有三种方式可用于根据 eTag 值、lastModified 值或两者同时进行条件请求的检查。对于条件 GETHEAD 请求,您可以将响应设置为 304(未修改)。而对于条件 POSTPUTDELETE 请求,则可以将响应设置为 412(前提条件失败),以防止并发修改。spring-doc.cadn.net.cn

静态资源

您应当为静态资源设置 Cache-Control 和条件响应头,以获得最佳性能。请参阅静态资源配置一节。spring-doc.cadn.net.cn

ETag过滤器

您可以使用 ShallowEtagHeaderFilter 来添加“浅层”eTag 值,这些值是根据响应内容计算得出的,从而节省带宽,但不会节省 CPU 时间。请参阅浅层 ETagspring-doc.cadn.net.cn