如何在 Spring Boot 中启用 HTTP 响应缓存

2023-12-10

我已经使用 Spring Boot 1.0.2 实现了 REST 服务器。我无法阻止 Spring 设置禁用 HTTP 缓存的 HTTP 标头。

我的控制器如下:

@Controller
public class MyRestController {
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> myMethod(
            HttpServletResponse httpResponse) throws SQLException {
        return new ResponseEntity<String>("{}", HttpStatus.OK);
    }
}

所有 HTTP 响应都包含以下标头:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: 0
Pragma: no-cache

我已尝试以下方法来删除或更改这些标头:

  1. Call setCacheSeconds(-1)在控制器中。
  2. Call httpResponse.setHeader("Cache-Control", "max-age=123")在控制器中。
  3. Define @Bean返回WebContentInterceptor我为此打电话setCacheSeconds(-1).
  4. 设置属性spring.resources.cache-period为 -1 或正值application.properties.

以上均未产生任何效果。如何在 Spring Boot 中禁用或更改所有或单个请求的这些标头?


事实证明,无缓存 HTTP 标头是由 Spring Security 设置的。这在中讨论http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers.

以下禁用 HTTP 响应标头Pragma: no-cache,但并没有解决问题:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Prevent the HTTP response header of "Pragma: no-cache".
        http.headers().cacheControl().disable();
    }
}

我最终对公共静态资源完全禁用了 Spring Security,如下所示(在与上面相同的类中):

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/static/public/**");
}

这需要配置两个资源处理程序以获得正确的缓存控制标头:

@Configuration
public class MvcConfigurer extends WebMvcConfigurerAdapter
        implements EmbeddedServletContainerCustomizer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // Resources without Spring Security. No cache control response headers.
        registry.addResourceHandler("/static/public/**")
            .addResourceLocations("classpath:/static/public/");

        // Resources controlled by Spring Security, which
        // adds "Cache-Control: must-revalidate".
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(3600*24);
    }
}

也可以看看在 Spring Boot 和 Spring Security 应用程序中提供静态 Web 资源.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring Boot 中启用 HTTP 响应缓存 的相关文章

随机推荐