Search code examples
spring-bootspring-webfluxhttp-caching

Disable HTTP cache in WebFlux


In Spring Boot MVC app I disable HTTP cache this way:

WebContentInterceptor cacheInterceptor = new WebContentInterceptor();
cacheInterceptor.setCacheSeconds(0);
cacheInterceptor.setUseExpiresHeader(true);
cacheInterceptor.setUseCacheControlHeader(true);
cacheInterceptor.setUseCacheControlNoStore(true);
registry.addInterceptor(cacheInterceptor);

How to do it in Spring Boot WebFlux app?


Solution

  • If you're using Spring Boot and you'd like to prevent caching for static resources, you can achieve that with the following configuration property:

    spring.web.resources.cache.cachecontrol.no-store=true
    

    If you'd like to disable caching for everything, including REST calls and views, etc; then you can implement a custom WebFilter that does just that and expose it as a bean in your application:

    class NoStoreWebFilter implements WebFilter {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            exchange.getResponse().getHeaders()
                    .setCacheControl(CacheControl.noStore().getHeaderValue());
            return chain.filter(exchange);
        }
    }