Oct 6, 2011 0
Making things @Cacheable
Performance optimizing with caching frameworks, or in general caching, like OSCache, EHCache is inevitable in software development and especially critically important in web development. If you want to serve contents from your data storages and if you’ve hunderds of requests – per minute – or even more, like on high-traffic portals, then it must be considered to cache your contents, objects, method calls, etc. in every layer efficiently. Most of ORM frameworks like Hibernate do support first-level and second level caching out-of-box and there are also many other caching strategies like distrubuted caching with Oracle Coherence or Jboss distributed caching facilities. But we won’t discuss in detail all of them. The aim of this post is to show application developers how to integrate custom caching mechanism easily using java annotations (Java 1.5+) from programmers’ point of view.
Think about the situation that you’re developing a website of which contents are supplied by a commercial partner in xml and you have to render these contents on-fly over a reliable connection and responsive server – or you can cache the contents in a relational database, but to reduce database request it’s a best practice to integrate custom caching in your service layer. Say, the contents are about weather informations from stations and you’re about to build a weather web application. Everytime your page gets called, without any caching mechanism your service has to call partner service also. It can bring about an overhead on your network and load on backend. Maybe just for that reason, you might rehandle your contract.
EHCache is a pretty good solution and a well known caching framework which’s broadly used to cache “data” programmaticaly – not only- creating and implementing your own CacheKeys. It is easier to integrate into spring web applications. But, things’re getting even better with ehcache-spring-annotations project on google code if the application deveper had a chance to cache some data, supplying some meta informations (god bless annotations) without any coding effort.
The common scenario is that we have a MVC application and the following controller handles user requests on “http://{yourhost.com}/{appcontext}/weatherchannel/index.html?sid=4567
“sid” stands for “station id” and passed as GET parameter to the controller.
@Controller @RequestMapping("/weatherchannel") public class WeatherChannelController { @Autowired private IWeatherDataGateway weatherGateway; @RequestMapping(value="/index.html", method=RequestMethod.GET) public String handleUserRequest(@RequestParam("sid") String stationId, ModelMap model) { List<weatherstationinfobean> stationInfos = weatherGateway.callPartnerEndpointRestfully(id); model.addAttribute("sinfos", stationInfos); return "stationinfo"; } } </weatherstationinfobean>


