在 Spring Boot 中启用 Http 缓存

Posted

技术标签:

【中文标题】在 Spring Boot 中启用 Http 缓存【英文标题】:Enable Http Cache in Spring Boot 【发布时间】:2016-08-10 17:11:15 【问题描述】:

从我的客户端,我正在从服务器查询一些枚举。现在,我想在服务器上查询过这些枚举后立即将它们缓存在客户端中。

我尝试如下设置Cache-Control

@CrossOrigin
@RequestMapping(value = "enums/name", method = RequestMethod.GET)
public List<String> getEnums( @PathVariable("name") String name, final HttpServletResponse response) 
    response.setHeader("Cache-Control", "max-age=3600");
    return myservice.findAllEnums(name);

响应标头似乎正确设置为Cache-control: max-age=3600。我还在我的安全配置中禁用了所有 http 标头,如下所示:

@Override 
protected void configure(final HttpSecurity http) throws Exception      
http.headers().cacheControl().disable(); 

不幸的是,响应没有缓存在浏览器中。一旦我查询资源,查询就会再次发送到服务器。

同时,我完全删除了 Spring Security,但它仍然无法正常工作。 我没有正确理解什么?我还需要配置什么?

【问题讨论】:

【参考方案1】:

关于 chrome 行为:Chrome back button doesn't respect the cache-control:no-cache header

【讨论】:

【参考方案2】:

好的,我注意到它适用于 IE,但不适用于 Chrome。 Chrome 的问题在于,如果您正在刷新页面,它会在请求的标头上设置Cache-control: max-age=0。这显然可以防止数据被缓存。然后,我使用指向我的应用程序的超链接创建了一个简单的 html,并通过此链接对其进行了刷新。因此,缓存按预期工作。

【讨论】:

【参考方案3】:

您需要检查是否有任何限制,因为 Spring Security 设置了无缓存 HTTP 标头。 您可以在这里获得更多相关信息:How to enable HTTP response caching in Spring Boot

【讨论】:

同时,我强制关闭了 Spring Security,但它仍然不起作用。

以上是关于在 Spring Boot 中启用 Http 缓存的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Spring Boot 中启用浏览器缓存

使用带有spring数据缓存的redis时如何启用分布式/集群缓存

在Spring Boot中启用Http2.0

如何在没有 SSL 配置的情况下使用 spring boot 和 tomcat 启用 http2

IDEA 中 Spring Boot 启用热部署

如何在 Spring Boot 和 Angular 中启用 CORS