更正CacheControl配置以指示永远不应缓存资源表示?

时间:2018-01-24 14:49:12

标签: java http jax-rs cache-control

private static final CacheControl NEVER;

static
{
    NEVER = new CacheControl();
    NEVER.setNoCache(true);
    NEVER.setMaxAge(-1);
    NEVER.setMustRevalidate(true);
    NEVER.setNoStore(true);
    NEVER.setProxyRevalidate(true);
    NEVER.setSMaxAge(-1);
}

我想配置一个CacheControl指令,该指令将向所有客户端和代理指示资源表示应该出于任何原因从不进行缓存。这是我从my research找到并阅读JavaDocs的内容。

上述配置中是否还有其他设置?

1 个答案:

答案 0 :(得分:2)

您的配置看起来不错,但我经常使用max-ages-maxage设置Cache-Control 0 -1也可以使用0

如果收件人不支持Cache-Control,您可能还需要将Expires标头设置为Cache-Control。来自RFC 7234

  

如果响应包含带有max-age指令的Expires字段,则收件人必须忽略s-maxage字段。同样,如果响应包含Expires指令,则共享缓存接收方必须忽略Expires字段。在这两种情况下,Cache-Control中的值仅适用于尚未实施@NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface NoCache {} 字段的收件人。

在JAX-RS中,您可以使用过滤器将此类标头添加到响应中,并使用名称绑定注释将过滤器绑定到特定资源方法或资源类。

首先定义名称绑定注释:

@NoCache

然后创建一个过滤器,将标题添加到响应中,并使用上面定义的@NoCache @Provider public class NoCacheFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { CacheControl cacheControl = new CacheControl(); cacheControl.setNoStore(true); cacheControl.setNoCache(true); cacheControl.setMustRevalidate(true); cacheControl.setProxyRevalidate(true); cacheControl.setMaxAge(0); cacheControl.setSMaxAge(0); response.getHeaders().add(HttpHeaders.CACHE_CONTROL, cacheControl.toString()); response.getHeaders().add(HttpHeaders.EXPIRES, 0); } } 注释对其进行注释:

@NoCache

然后使用@Path("/foo") public class MyResource() { @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public String wontCache() { ... } }

将上面定义的过滤器绑定到您的端点
@NoCache

如果您想要全局过滤器,则无需定义@Override protected void onDestroyView(@NonNull View view) { super.onDestroyView(view); unbinder.unbind(); unbinder = null; } 注释。