下面显示的RESTful方法代码,我想使用缓存来快速响应,但是从request.evaluatePreconditions(tag);
我总是得到null
。
@GET
@Path("e_tag")
@Produces(MediaType.TEXT_PLAIN)
public Response getItWithETag(@Context Request request) {
Response.ResponseBuilder rb;
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(1200);
EntityTag tag = new EntityTag(GOT_IT.hashCode() + "");
rb = request.evaluatePreconditions(tag);
if (rb != null) {
return rb.cacheControl(cacheControl).tag(tag).build();
} else {
return Response.ok(GOT_IT).cacheControl(cacheControl).tag(tag).build();
}
}
测试代码:
@Test
public void testETag() throws InterruptedException {
WebTarget webTarget = target("rest").path("e_tag");
Response head = webTarget.request().get();
System.out.println(head.getStatus() + "\t" + head.getEntityTag());
Assert.assertEquals(200, head.getStatus());
Thread.sleep(1000);
Response head1 = webTarget.request().get();
System.out.println(head1.getStatus() + "\t" + head1.getEntityTag());
Assert.assertEquals(304, head1.getStatus());
}
我无法获得理想的结果。
答案 0 :(得分:1)
测试代码在http头中缺少If-None-Match。正确的方法:
@Test
public void testETag() throws InterruptedException {
WebTarget webTarget = target("rest").path("e_tag").queryParam("userId", "eric");
Response head = webTarget.request().get();
EntityTag eTag = head.getEntityTag();
System.out.println(head.getStatus() + "\t" + eTag);
Assert.assertEquals(200, head.getStatus());
Thread.sleep(1000);
Response head1 = webTarget.request().header("If-None-Match", eTag).get();
System.out.println(head1.getStatus() + "\t" + head1.getEntityTag());
Assert.assertEquals(304, head1.getStatus());
}