HTTP 快取

HTTP 快取可以顯著提升網路應用程式的效能。HTTP 快取圍繞 Cache-Control 回應標頭,以及後續的條件式請求標頭 (例如 Last-ModifiedETag)。Cache-Control 建議私有 (例如,瀏覽器) 和公用 (例如,Proxy) 快取如何快取和重複使用回應。如果內容沒有變更,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 快取的明確支援。我們建議這樣做,因為資源的 lastModifiedETag 值需要在與條件式請求標頭進行比較之前計算。控制器可以將 ETag 標頭和 Cache-Control 設定新增至 ResponseEntity,如下列範例所示

  • 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) 回應,其中包含空的本文。否則,ETagCache-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 值或兩者的條件式請求。對於條件式 GETHEAD 請求,您可以將回應設定為 304 (NOT_MODIFIED)。對於條件式 POSTPUTDELETE,您可以改為將回應設定為 412 (PRECONDITION_FAILED),以防止並行修改。

靜態資源

您應該使用 Cache-Control 和條件式回應標頭來提供靜態資源,以獲得最佳效能。請參閱關於配置靜態資源的章節。

ETag 篩選器

您可以使用 ShallowEtagHeaderFilter 來新增從回應內容計算出的「淺層」eTag 值,從而節省頻寬,但不能節省 CPU 時間。請參閱 Shallow ETag