Search code examples
javarestjersey

How to cache response with Jersey?


I am trying to develop restful API using Jersey.I have GET API's for a particular get operation my GET is taking same time from the same client. Is it possible to cache response? Any pointers is appreciated.

Thanks


Solution

  • You can use CacheControl, eTag - follow below example code

    // In your jersey method
        final EntityTag eTag = new EntityTag(resource.getId() + "_" +
         resource.getLastModified().getTime());
        final CacheControl cacheControl = new CacheControl();
        cacheControl.setMaxAge(-1);
    
        ResponseBuilder builder = request.evaluatePreconditions(
             resource.getLastModified(), eTag);
    
        // the resoruce's information was modified, return it
        if (builder == null) {
             builder = Response.ok(resource);
        }
    
        // the resource's information was not modified, return a 304
    
        return builder.cacheControl(cacheControl).lastModified(
             resource.getLastModified()).tag(eTag).build();
    

    Replace resource with your Resource instance.