在 Spring 引导中启用 Http 缓存

Enable Http Cache in Spring Boot

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

我尝试设置 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);
}

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

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

很遗憾,响应未缓存在浏览器中。我一查询资源,查询就会再次转到服务器。

与此同时,我完全删除了 Spring 安全性,但它仍然不起作用。 我没有正确理解什么?我还需要配置什么?

您需要检查是否有任何限制,因为 no-cache HTTP headers 是由 Spring 安全设置的。 您可以在这里获得更多相关信息:How to enable HTTP response caching in Spring Boot

好的,我注意到它可以与 IE 一起使用,但不能与 Chrome 一起使用。 Chrome 的问题在于,如果您正在刷新页面,它会在请求的 header 上设置 Cache-control: max-age=0。这显然会阻止数据被缓存。然后,我使用 hyperlink 为我的应用程序创建了一个简单的 html,并通过此 link 刷新它。因此,缓存按预期工作。

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