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

Sam*_*nen 47 java spring spring-mvc spring-security spring-boot

我使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: 0
Pragma: no-cache
Run Code Online (Sandbox Code Playgroud)

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

  1. 呼叫setCacheSeconds(-1)控制器.
  2. 呼叫httpResponse.setHeader("Cache-Control", "max-age=123")控制器.
  3. 定义我调用的@Bean返回值.WebContentInterceptorsetCacheSeconds(-1)
  4. 将属性设置spring.resources.cache-period为-1或正值application.properties.

以上都没有任何影响.如何在Spring Boot中为所有或单个请求禁用或更改这些标头?

Sam*_*nen 53

结果是由Spring Security设置的无缓存HTTP头.这在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅Spring Boot和Spring Security应用程序中的静态Web资源.

  • 如果您希望为http://stackoverflow.com/a/36459244/759042中列出的特定控制器操作使用不同的Cache-Control标头,则无需完全关闭Spring Security. (2认同)

Mer*_*erv 6

在Spring Boot中,有很多方法可以进行HTTP缓存。使用Spring Boot 2.1.1和其他Spring Security 5.1.1。

1.对于在代码中使用resourcehandler的资源:

您可以通过这种方式添加资源的自定义扩展。

registry.addResourceHandler
Run Code Online (Sandbox Code Playgroud)

用于添加uri路径以获取资源

.addResourceLocations
Run Code Online (Sandbox Code Playgroud)

用于设置文件系统中资源所在的位置(给定的是与classpath的相对关系,但也可以使用file :: //的绝对路径。)

.setCacheControl
Run Code Online (Sandbox Code Playgroud)

用于设置缓存头(自我解释。)

Resourcechain和resolver是可选的(在这种情况下,它与默认值完全相同。)

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

2.对于使用应用程序属性配置文件的资源

与上面相同,减去了特定的模式,但现在是config。 此配置将应用于列出的静态位置中的所有资源。

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/
Run Code Online (Sandbox Code Playgroud)

3.在控制器级别

这里的响应是作为参数注入到控制器方法中的HttpServletResponse。

no-cache, must-revalidate, private
Run Code Online (Sandbox Code Playgroud)

getHeaderValue将缓存选项输出为字符串。例如

response.setHeader(HttpHeaders.CACHE_CONTROL,
            CacheControl.noCache()
                    .cachePrivate()
                    .mustRevalidate()
                    .getHeaderValue());
Run Code Online (Sandbox Code Playgroud)


dap*_*tci 5

我已经找到了这个Spring扩展名:https : //github.com/foo4u/spring-mvc-cache-control

您只需要执行三个步骤。

步骤1(pom.xml):

<dependency>
    <groupId>net.rossillo.mvc.cache</groupId>
    <artifactId>spring-mvc-cache-control</artifactId>
    <version>1.1.1-RELEASE</version>
    <scope>compile</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

步骤2(WebMvcConfiguration.java):

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CacheControlHandlerInterceptor());
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤3(控制器):

@Controller
public class MyRestController {

    @CacheControl(maxAge=31556926)
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> myMethod(
            HttpServletResponse httpResponse) throws SQLException {
        return new ResponseEntity<String>("{}", HttpStatus.OK);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

可以通过以下方式覆盖特定方法的默认缓存行为:

@Controller
public class MyRestController {
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> myMethod(
            HttpServletResponse httpResponse) throws SQLException {
        return new ResponseEntity.ok().cacheControl(CacheControl.maxAge(100, TimeUnit.SECONDS)).body(T)
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

61110 次

最近记录:

6 年,3 月 前