显式禁用 REST 服务的缓存

Explicitly disable caching for REST services

我要将 Cache-Control: must-revalidate,no-cache,no-store 应用于来自后端 REST 服务的所有响应。我有两个问题:

编辑:找到这个:https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers#cache-prevention。是说当没有明确配置时浏览器可能会选择缓存,所以这意味着是的,如果我想确保禁用缓存,应该配置它。

我认为默认情况下它是禁用的。虽然有一些机制可以启用缓存以提高性能:

这里有一个关于如何启用缓存的很好的解释:

[来源:Heroku Dev Center]

Time-based cache headers

In HTTP 1.1 the Cache-Control header specifies the resource caching behavior as well as the max age the resource can be cached. As an example, this response would be cached for one day:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: private, max-age=86400
Last-Modified: Thu, 07 Feb 2013 11:56 EST

Here is a list of all the available Cache-Control tokens and their meaning:

  • private only clients (mostly the browser) and no one else in the chain (like a proxy) should cache this
  • public any entity in the chain can cache this
  • no-cache should not be cached anyway
  • no-store can be cached but should not be stored on disk (most browsers will hold the resources in memory until they will be quit)
  • no-transform the resource should not be modified (for example shrink image by proxy)
  • max-age how long the resource is valid (measured in seconds)
  • s-maxage same like max-age but this value is just for non clients

这是一个带有 CDI 缓存控制注释的示例:

[来源:abhirockzz.wordpress.com]

@Path("/testcache")
public class RESTfulResource {
    @Inject
    @CachControlConfig(maxAge = 20)
    CacheControl cc;

    @GET
    @Produces("text/plain")
    public Response find() {
        return Response.ok(UUID.randomUUID().toString()).cacheControl(cc).build();
    }
}

简而言之:是的,即使没有显式控件存在,缓存也可能缓存响应,您需要明确禁止它。

HTTP caching specification Section 3 lists when the response is forbidden to be cached. It suggests that the response may be cached as long as the response code is cacheable. A list of cacheable response codes is in the HTTP specification section 6.1:

Responses with status codes that are defined as cacheable by default (e.g., 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501 in this specification) can be reused by a cache with heuristic expiration unless otherwise indicated by the method definition or explicit cache controls...

“启发式过期”定义为在不存在显式控件时指定的过期时间。 (HTTP caching specification section 4.2.)