javascript
Spring MVC 中的http Caching
文章目錄
- 過期時間
- Last-Modified
- ETag
- Spring ETag filter
Spring MVC 中的http Caching
Cache 是HTTP協(xié)議中的一個非常重要的功能,使用Cache可以大大提高應(yīng)用程序的性能,減少數(shù)據(jù)的網(wǎng)絡(luò)傳輸。
通常來說我們會對靜態(tài)資源比如:圖片,CSS,JS文件等做緩存。同樣的我們可以使用HTTP Cache配合Spring MVC來做動態(tài)資源的緩存。
那么什么時候使用動態(tài)資源的緩存呢?
只有當(dāng)這個資源不經(jīng)常更新或者你確切的知道該資源什么時候更新的時候就可以使用HTTP Cache了。
HTTP Cache是通過請求頭來實現(xiàn)的,主要有三種方式:過期時間,最后更新時間和Etag。
其中過期時間是客戶端驗證,最后更新時間和Etag是服務(wù)器端驗證。
過期時間
過期時間又有兩種方式,分別是Cache-Control和Expires頭。
在Cache-Control中,我們可以設(shè)置它的maxAge,超出該時間后,該資源才會被再次請求。如下所示:
@GetMapping("/{id}") ResponseEntity<Product> getProduct(@PathVariable long id) {// …CacheControl cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES);return ResponseEntity.ok().cacheControl(cacheControl).body(product); }我們也可以在Head中設(shè)置Expires屬性。Expires的時間需要是標(biāo)準(zhǔn)時間格式,如下:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format如果要在java中使用,參考如下的例子:
@GetMapping("/forecast") ResponseEntity<Forecast> getTodaysForecast() {// ...ZonedDateTime expiresDate = ZonedDateTime.now().with(LocalTime.MAX);String expires = expiresDate.format(DateTimeFormatter.RFC_1123_DATE_TIME);return ResponseEntity.ok().header(HttpHeaders.EXPIRES, expires).body(weatherForecast); }如果Cache-Control和Expires同時出現(xiàn),則會優(yōu)先使用 Cache-Control。
Last-Modified
它的驗證邏輯是這樣的,客戶端會根據(jù)上次請求得到的Last-Modified設(shè)置它的If-Modified-Since,服務(wù)器端接收到了這個屬性之后可以跟之前的進行比較,如果相同則可以返回一個空的body。如下所示:
@GetMapping("/{id}") ResponseEntity<Product> getProduct(@PathVariable long id, WebRequest request) {Product product = repository.find(id);long modificationDate = product.getModificationDate().toInstant().toEpochMilli();if (request.checkNotModified(modificationDate)) {return null;}return ResponseEntity.ok().lastModified(modificationDate).body(product); }ETag
Last-Modified的時間只能精確到秒,如果還需要更細粒度的話,就需要用到ETag了。
ETag可以看成當(dāng)前時刻某個資源的唯一標(biāo)記,你可以取該資源的hash值作為ETag。
下面是它的一種實現(xiàn):
@GetMapping("/{id}") ResponseEntity<Product> getProduct(@PathVariable long id, WebRequest request) {Product product = repository.find(id);String modificationDate = product.getModificationDate().toString();String eTag = DigestUtils.md5DigestAsHex(modificationDate.getBytes());if (request.checkNotModified(eTag)) {return null;}return ResponseEntity.ok().eTag(eTag).body(product); }Spring ETag filter
Spring提供了一個ShallowEtagHeaderFilter來根據(jù)返回的內(nèi)容自動為你生成Etag。
@Bean public FilterRegistrationBean filterRegistrationBean () {ShallowEtagHeaderFilter eTagFilter = new ShallowEtagHeaderFilter();FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter(eTagFilter);registration.addUrlPatterns("/*");return registration; }請注意, ETag計算可能會影響性能。
更多教程請參考 flydean的博客
超強干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的Spring MVC 中的http Caching的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scala教程之:可见性规则
- 下一篇: 新版gitbook导出pdf