Spring Web MVC框架(十) HTTP缓存

Spring的缓存控制类

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

静态资源的HTTP缓存

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

@Configuration
@EnableWebMvc
public 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不会做任何更改。

@RequestMapping
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值