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的内容。
答案 0 :(得分:2)
您的配置看起来不错,但我经常使用max-age
和s-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;
}
注释。