Spring Web MVC框架(十) HTTP缓存

来源:互联网 发布:网络服务商地址 编辑:程序博客网 时间:2024/06/15 06:45

Spring的缓存控制类

合理利用HTTP缓存,可以提高应用程序的性能。Spring当然也对HTTP缓存提供了支持。HTTP缓存最基础的类就是org.springframework.http.CacheControl,我们可以使用该类提供的各种工厂方法来得到一个CacheControl对象,然后将它添加到各种方法中。常用的工厂方法有maxAge、cachePublic、noTransform等等。它们都返回CacheControll对象,所以我们也可以链式调用它们。

静态资源的HTTP缓存

如果使用Java配置的话,重写WebMvcConfigurerAdapteraddResourceHandlers方法即可。

@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**")                .addResourceLocations("/static/")                .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());    }}

如果使用XML配置的话,在mvc:resources中添加子元素mvc:cache-control即可。

<mvc:resources mapping="/static/**" location="/static/">    <mvc:cache-control max-age="3600" cache-public="true"/></mvc:resources>

控制器中的HTTP缓存

在控制器中也可以控制HTTP缓存。常用的一种做法是使用ResponseEntity,它有一个cacheControl方法,可以用来设置HTTP缓存。Spring不仅会在实际响应的头中添加Cache-Control信息,而且会在客户端满足缓存条件的时候返回304未更改响应码。

@RequestMapping("manyUsers.xml")public ResponseEntity<List<User>> manyUsersXml() {    return ResponseEntity.ok()            .cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS))            .body(manyUsers);}

当然,在普通的返回视图名的控制器方法中也可以使用HTTP缓存。来看看Spring提供的一个例子。在这里有两个需要注意的地方:一是request.checkNotModified(lastModified)方法,它用来判断页面是否发生过更改,并会设置相应的响应头;二是当内容没有更改直接返回null,这告诉Spring不会做任何更改。

@RequestMappingpublic String myHandleMethod(WebRequest webRequest, Model model) {    long lastModified = // 1. application-specific calculation    if (request.checkNotModified(lastModified)) {        // 2. shortcut exit - no further processing necessary        return null;    }    // 3. or otherwise further request processing, actually preparing content    model.addAttribute(...);    return "myViewName";}

request.checkNotModified方法有三个变种:
- request.checkNotModified(lastModified)将’If-Modified-Since’或’If-Unmodified-Since’请求头与lastModified相比。
- request.checkNotModified(eTag)将’If-None-Match’请求头和eTag相比较。
- request.checkNotModified(eTag, lastModified)同时会验证这两者。

0 0