博客
关于我
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/

你可能感兴趣的文章
PhpStorm配置远程xdebug
查看>>
phpstudy+iis搭建php项目
查看>>
phpStudy安装教程
查看>>
phpstudy搭建网站,通过快解析端口映射外网访问
查看>>
phpstudy站点域名管理
查看>>
phpunit
查看>>
PHPUnit单元测试对桩件(stub)和仿件对象(Mock)的理解
查看>>
phpweb成品网站最新版(注入、上传、写shell)
查看>>
phpWhois 项目推荐
查看>>
Redis事务详解,吃透数据库没你想的那么难
查看>>
phpwind部署问题
查看>>
PHP_CodeIgniter Github实现个人空间
查看>>
php_crond:一个基于多进程的定时任务系统-支持秒粒度的任务配置
查看>>
PHP__call __callStatic
查看>>
PHP——修改数据库1
查看>>
PHP——封装Curl请求方法支持POST | DELETE | GET | PUT 等
查看>>
PHP——底层运行机制与原理
查看>>
php一句话图片运行,【后端开发】php一句话图片木马怎么解析
查看>>
PHP三方登录,移动端与服务端交互
查看>>
Redis事务深入解析和使用
查看>>