博客
关于我
Spring MVC 中的http Caching
阅读量:421 次
发布时间:2019-03-06

本文共 2415 字,大约阅读时间需要 8 分钟。

Cache在HTTP协议中扮演着重要角色,它能够显著提升应用性能并减少数据传输负担。对于静态资源(如图片、CSS、JS文件等)来说,缓存是必不可少的。然而,动态资源的缓存也是可行的,尤其是在资源不经常更新或明确知道更新时间的情况下。

Cache-Control

Cache-Control是一个强大的工具,用于指定缓存策略。它的maxAge属性允许指定缓存时间,超过该时间后,客户端会重新请求资源。以下是一个示例:

@GetMapping("/{id}")ResponseEntity
getProduct(@PathVariable long id) { // … CacheControl cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES); return ResponseEntity.ok() .cacheControl(cacheControl) .body(product);}

此外,Expires头也可以用于设置缓存过期时间,时间格式需遵循标准规范。以下是一个示例:

@GetMapping("/forecast")ResponseEntity
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同时存在,Cache-Control优先生效。

Last-Modified

Last-Modified通过比较客户端的If-Modified-Since头和服务器端的资源修改日期来实现缓存验证。服务器端可以根据修改日期返回304 Not Modified响应,避免不必要的数据传输。以下是一个示例:

@GetMapping("/{id}")ResponseEntity
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可以使用资源的哈希值作为唯一标识符。以下是一个示例:

@GetMapping("/{id}")ResponseEntity
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,可以根据返回内容自动为资源生成ETag。以下是一个示例:

@Beanpublic FilterRegistrationBean filterRegistrationBean() {    ShallowEtagHeaderFilter eTagFilter = new ShallowEtagHeaderFilter();    FilterRegistrationBean registration = new FilterRegistrationBean();    registration.setFilter(eTagFilter);    registration.addUrlPatterns("/*");    return registration;}

需要注意的是,ETag的计算可能会影响性能。

通过合理配置Cache-Control、Last-Modified和ETag,可以有效提升Spring MVC应用的性能和用户体验。

转载地址:http://ggnuz.baihongyu.com/

你可能感兴趣的文章
PATA1038题解(需复习)
查看>>
Patching Array
查看>>
PatchMatchStereo可能会需要的Rectification
查看>>
Path does not chain with any of the trust anchors
查看>>
Path形状获取字符串型变量数据
查看>>
PAT甲级——1001 A+B Format (20分)
查看>>
Skywalking原理
查看>>
PAT甲级——1006 Sign In and Sign Out (25分)
查看>>
PAT甲级——1007 Maximum Subsequence Sum (25分)
查看>>
PAT甲级——1009 Product of Polynomials (25分)(最后一个测试点段错误)
查看>>
Spring对jdbc的支持
查看>>
PayPal网站付款标准版(for PHP)
查看>>
Paystack Android SDK 集成与使用指南
查看>>
pbf格式详解,javascript加载导出pbf文件示例
查看>>
PBOC2.0与3.0的区别
查看>>
PbootCMS entrance.php SQL注入漏洞复现
查看>>
PbootCMS 前台RCE漏洞复现
查看>>
PBT
查看>>
PB级分析型数据库ClickHouse的应用场景和特性
查看>>
pc3-12800
查看>>