Last active
March 27, 2016 09:56
-
-
Save abhirockzz/4efa4dc288ac4e088d3c to your computer and use it in GitHub Desktop.
Improving GET request performance in JAX-RS by using the ETag header
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") | |
@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