Created
May 9, 2014 22:23
-
-
Save cchacin/a43cc2b88ccf621e8bbb to your computer and use it in GitHub Desktop.
JAX-RS Conditional Cache Headers -> https://devcenter.heroku.com/articles/jax-rs-http-caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Path("/books") | |
public class BookResource { | |
// less bandwidth | |
@GET | |
@Path("/{id}") | |
public Response getBook(@PathParam("id") long id, @Context Request request){ | |
Book myBook = getBookFromDB(id); | |
CacheControl cc = new CacheControl(); | |
cc.setMaxAge(86400); | |
EntityTag etag = new EntityTag(Integer.toString(myBook.hashCode())); | |
ResponseBuilder builder = request.evaluatePreconditions(etag); | |
// cached resource did change -> serve updated content | |
if(builder == null){ | |
builder = Response.ok(myBook); | |
builder.tag(etag); | |
} | |
builder.cacheControl(cc); | |
return builder.build(); | |
} | |
@PUT | |
@Path("/{id}") | |
@Consumes("application/json") | |
public Response getBook(@PathParam("id") long id, @Context Request request, Book updatedBook){ | |
Book myBook = getBookFromDB(id); | |
EntityTag etag = new EntityTag(Integer.toString(myBook.hashCode())); | |
ResponseBuilder builder = request.evaluatePreconditions(etag); | |
// client is not up to date (send back 412) | |
if(builder != null){ | |
return builder.build(); | |
} | |
updateBookInDB(updatedBook); | |
builder = Response.noContent(); | |
return builder.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obviously, if we are using cURL or we don't instruct to our client to use this advantages nothing happen, but is not a issue, simply we aren't using an available feature :)
In JAX-RS 2.0 we can use something like this: