本文共 2415 字,大约阅读时间需要 8 分钟。
Cache在HTTP协议中扮演着重要角色,它能够显著提升应用性能并减少数据传输负担。对于静态资源(如图片、CSS、JS文件等)来说,缓存是必不可少的。然而,动态资源的缓存也是可行的,尤其是在资源不经常更新或明确知道更新时间的情况下。
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通过比较客户端的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);} 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 提供了一个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/