Skip to content

Instantly share code, notes, and snippets.

@abhirockzz
Last active March 27, 2016 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhirockzz/4efa4dc288ac4e088d3c to your computer and use it in GitHub Desktop.
Save abhirockzz/4efa4dc288ac4e088d3c to your computer and use it in GitHub Desktop.
Improving GET request performance in JAX-RS by using the ETag header
@Path("books")
@Stateless
public class BooksResource_2{
@PersistenceContext
EntityManager em;
@Context
Request request;
@Path("{id}")
@GET
@Produces("application/json")
public Response getById(@PathParam("id") String id){
Book book = em.find(Book.class, id); //get book info from backend DB
String uniqueHashForBook = uniqueHashForBook(book); //calculate tag value based on your custom implementation
EntityTag etag = new EntityTag(uniqueHashForBook) //instantiate the object
ResponseBuilder evaluationResultBuilder = request.evaluatePreconditions(etag); //let JAX-RS do the math!
if(evaluationResultBuilder == null){
evaluationResultBuilder = Response.ok(book); //resource was modified, send latest info (and HTTP 200 status)
}else{
System.out.println("Resource not modified - HTTP 304 status");
}
CacheControl caching = ...; //decide caching semantics
evaluationResultBuilder.cacheControl(caching)
.tag(etag); //add metadata
return evaluationResultBuilder.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment