One of the tasks that I’m currently working on (albeit at a pace not to my liking) is to add a HTTP response cache implementation in ehcache’s web module. This will be particularly useful for REST-based clients to optionally cache the responses of the GET requests.

Java has got a built-in mechanism for response caching. This was introduced in Java 5 by adding three abstract classes in java.net package: ResponseCache, CacheRequest, CacheResponse. You need to extend these classes for your own cache implementation.

The flow of events is something like the following:

  • A concrete class of ResponseCache registers with the system by using the static method ResponseCache.setDefault(ResponseCache).
  • There are two methods in the ResponseCache that are invoked by the protocol handlers. get() returns a CacheResponse and put() returns a CacheRequest.
  • When you create a URLConnection and attempt to read content the appropriate stream handler is created and it checks for the content in the cache by invoking ResponseCache.get().
  • If the content is found in the cache, it is returned. Otherwise a request is sent to the origin server, the received response is then passed on to ResponseCache.put() to see if the content is cacheable (based on the response headers) and possiblly store it in the cache.

Bulk of the work of cache-ability determination, placing the resource content in the cache, evicting the content based on the Expires or Date headers, and retrieving the resource will be done by your own cache implementation. Here is where I will be spending bulk of my time satisfying the intricacies of RFC-2616 (Chapter 13) that deals with Caching in HTTP.

This implementation works only for the clients using URLConnection to connect, as Java’s response cache mechanism described above works only for URLConnection. But once a pattern is set hopefully we can extend or write adapters for the clients using other mechanisms like Apache Common’s HttpClient.

Hope to elaborate more on this soon …

Share and Enjoy:
  • del.icio.us
  • DZone
  • Digg
  • StumbleUpon
  • Technorati
  • Reddit
  • Facebook
  • Twitter
  • Google Bookmarks
  • FriendFeed
  • Tumblr
  • HackerNews

You may also like:

  1. HTTP Response Caching with Ehcache
  2. Java’s HTTP Handler and Cache Validation Issues