Spring的緩存控制類
合理利用HTTP緩存,可以提高應用程序的性能。Spring當然也對HTTP緩存提供了支持。HTTP緩存最基礎的類就是org.springframework.http.CacheControl
,我們可以使用該類提供的各種工廠方法來得到一個CacheControl
對象,然后將它添加到各種方法中。常用的工廠方法有maxAge、cachePublic、noTransform等等。它們都返回CacheControll對象,所以我們也可以鏈式調用它們。
靜態資源的HTTP緩存
如果使用Java配置的話,重寫WebMvcConfigurerAdapter
的addResourceHandlers
方法即可。
@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)同時會驗證這兩者。