How to enable HTTP response caching in Spring Boot

前端 未结 8 1911
我寻月下人不归
我寻月下人不归 2020-11-27 12:17

I have implemented a REST server using Spring Boot 1.0.2. I\'m having trouble preventing Spring from setting HTTP headers that disable HTTP caching.

My controller is

8条回答
  •  庸人自扰
    2020-11-27 12:59

    There are a lot of ways in spring boot for http caching. Using spring boot 2.1.1 and additionally spring security 5.1.1.

    1. For resources using resourcehandler in code:

    You can add customized extensions of resources this way.

    registry.addResourceHandler
    

    Is for adding the uri path where to get the resource

    .addResourceLocations
    

    Is for setting the location in the filesystem where the resources are located( given is a relative with classpath but absolute path with file::// is also possible.)

    .setCacheControl
    

    Is for setting the cache headers (self explanatory.)

    Resourcechain and resolver are optional (in this case exactly as the default values.)

    @Configuration
    public class CustomWebMVCConfig implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/*.js", "/*.css", "/*.ttf", "/*.woff", "/*.woff2", "/*.eot",
                "/*.svg")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS)
                        .cachePrivate()
                        .mustRevalidate())
                .resourceChain(true)
                .addResolver(new PathResourceResolver());
        }
    }
    

    2. For resources using application properties config file

    Same as above, minus the specific patterns, but now as config. This configuration is applied to all resources in the static-locations listed.

    spring.resources.cache.cachecontrol.cache-private=true
    spring.resources.cache.cachecontrol.must-revalidate=true
    spring.resources.cache.cachecontrol.max-age=31536000
    spring.resources.static-locations=classpath:/static/
    

    3. At controller level

    Response here is the HttpServletResponse injected in the controller method as parameter.

    no-cache, must-revalidate, private
    

    getHeaderValue will output the cache options as string. e.g.

    response.setHeader(HttpHeaders.CACHE_CONTROL,
                CacheControl.noCache()
                        .cachePrivate()
                        .mustRevalidate()
                        .getHeaderValue());
    

提交回复
热议问题