Spring MVC 中的http Caching
Spring MVC 中的http Caching
Cache 是HTTP协议中的一个非常重要的功能,使用Cache可以大大提高应用程序的性能,减少数据的网络传输。
通常来说我们会对静态资源比如:图片,CSS,JS文件等做缓存。同样的我们可以使用HTTP Cache配合Spring MVC来做动态资源的缓存。
那么什么时候使用动态资源的缓存呢?
只有当这个资源不经常更新或者你确切的知道该资源什么时候更新的时候就可以使用HTTP Cache了。
HTTP Cache是通过请求头来实现的,主要有三种方式:过期时间,最后更新时间和Etag。
其中过期时间是客户端验证,最后更新时间和Etag是服务器端验证。
过期时间
过期时间又有两种方式,分别是Cache-Control和Expires头。
在Cache-Control中,我们可以设置它的maxAge,超出该时间后,该资源才会被再次请求。如下所示:
@GetMapping("/{id}")
ResponseEntity<Product> getProduct(@PathVariable long id) {
// …
CacheControl cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES);
return ResponseEntity.ok()
.cacheControl(cacheControl)
.body(product);
}
我们也可以在Head中设置Expires属性。Expires的时间需要是标准时间格式,如下:
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同时出现,则会优先使用 Cache-Control。
Last-Modified
它的验证逻辑是这样的,客户端会根据上次请求得到的Last-Modified设置它的If-Modified-Since,服务器端接收到了这个属性之后可以跟之前的进行比较,如果相同则可以返回一个空的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可以看成当前时刻某个资源的唯一标记,你可以取该资源的hash值作为ETag。
下面是它的一种实现:
@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来根据返回的内容自动为你生成Etag。
@Bean
public FilterRegistrationBean filterRegistrationBean () {
ShallowEtagHeaderFilter eTagFilter = new ShallowEtagHeaderFilter();
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(eTagFilter);
registration.addUrlPatterns("/*");
return registration;
}
请注意, ETag计算可能会影响性能。
更多教程请参考 flydean的博客
Spring MVC 中的http Caching的更多相关文章
- Spring mvc中@RequestMapping 6个基本用法
Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: Java代码 @Reques ...
- spring mvc中使用freemark的一点心得
参考文档: FreeMarker标签与使用 连接http://blog.csdn.net/nengyu/article/details/6829244 freemarker学习笔记--指令参考: ht ...
- Http请求中Content-Type讲解以及在Spring MVC中的应用
引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...
- Spring mvc中@RequestMapping 6个基本用法小结(转载)
小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMapping(value="/departments" ...
- Spring MVC中处理静态资源的多种方法
处理静态资源,我想这可能是框架搭建完成之后Web开发的”头等大事“了. 因为一个网站的显示肯定会依赖各种资源:脚本.图片等,那么问题来了,如何在页面中请求这些静态资源呢? 还记得Spring MVC中 ...
- Spring MVC 中的基于注解的 Controller【转】
原文地址:http://my.oschina.net/abian/blog/128028 终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 H ...
- spring mvc中的文件上传
使用commons-fileupload上传文件所需要的架包有:commons-fileupload 和common-io两个架包支持,可以到Apache官网下砸. 在配置文件spring-mvc.x ...
- spring mvc中的valid
当你希望在spring mvc中直接校验表单参数时,你可以采用如下操作: 声明Validator的方式: 1.为每一个Controller声明一个Validator @Controller publi ...
- spring mvc中的@PathVariable(转)
鸣谢:http://jackyrong.iteye.com/blog/2059307 ------------------------------------------------ spring m ...
随机推荐
- P1006 传纸条(二维、三维dp)
P1006 传纸条 输入输出样例 输入 #1 复制 3 3 0 3 9 2 8 5 5 7 0 输出 #1 复制 34 说明/提示 [限制] 对于 30% 的数据,1≤m,n≤10: 对于 100% ...
- 1042 Shuffling Machine (20分)(水)
Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techn ...
- sqlchemy查询的其他操作
sqlalchemy的数据查询排序 1 .正序排序:session.query(model).order_by(model.attr).all() session.query(model).order ...
- MySQL数据库三
MySQL数据库三 多表查询: 有条件的内连接 将两张表根据相同的id连接起来 select * from info join details on info.id = details.id sele ...
- C语言学生管理系统完善版
#include<stdio.h>#include<string.h>#include <stdlib.h>#define M 100struct score ...
- JAVA中基本类型和包装类之间的相互转换
转自:https://www.imooc.com/code/2250 仅做个人学习记录之用,侵删. 基本类型和包装类之间经常需要互相转换,以 Integer 为例(其他几个包装类的操作雷同哦): 在 ...
- 37.3 net--TcpDemo1 大小写转换
需求:使用TCP协议发送数据,并将接收到的数据转换成大写返回 启动方式:先打开服务端,再打开客户端 客户端 package day35_net_网络编程.tcp传输; import java.io.I ...
- django 前后台传递数据
前几天,我们完成了用django orm对数据进行操作.接下来,我们要把数据从后台放到前台. 1.用get方式传值 get:就是在URL拼接字符串,在后台,用request.get方式取 2.用pos ...
- Go语言 可变参数
最近与同事讨论时,提到Go语言的可变参数,之前没有总结过相关知识点,今天我们介绍一下Go语言的可变参数. 可变参数(Variable Parameters):参数数量可变的函数称之为可变参数函数,主要 ...
- 测量C++程序运行时间
有个很奇怪的现象,我自认为写得好的文章阅读量只有一百多,随手写的却有一千多--要么是胡搞,要么是比较浅显.纵观博客园里众多阅读过万的文章,若非绝世之作,则必为介绍入门级知识的短文.为了让我的十八线博客 ...