简体   繁体   中英

How to maintain cache for Java/J2EE web application?

I am developing an application for that every time I need to connect to the service. I want to save each search in my cache for further use. Is there any option to do that?

I heard about Memcached. But I didn't find any correct site for reference. Can we use Ehcache as we use in Hibernate?

There are various caching solutions in Java. Among them are Infinispan, EhCache and OSCache.

All of them can also be used standalone, eg none of them were exclusively build to function as a Hibernate caching provider.

Functionalities between caches differ a little. Infinispan for instance provides first class support for transactions (meaning an item won't be inserted into the cache if the transaction in which the item was inserted rollbacks). EhCache has great support for really large in-process but off heap storage for cache.

OSCache comes with very handy tags to cache content on JSP pages (but that doesn't work with eg JSF).

Most of them are capable of doing the typical spill over to disk thing, and have some mechanisms to invalidate stale entries. Infinispan for instance has eviction policies, and those really remove stale entries from the cache (saving memory). OSCache on its turn never really removes an entry from the cache, but marks it as stale. When the entry is accessed, the caller is alerted to refresh the entry (used to be an exception, but might be different now).

Those things are typically what sets a "cache" apart from a simple concurrent hashmap. If your requirements are modest, don't overlook this simple solution though. A cache can be somewhat hard to configure and a concurrent map in application scope may also suffice for you.

You can cache data on a per user basis (ie session) with OSCache's jsp tags very easily. For example, imagine a web application, where a particular users "worklist" hasn't changed, then always serve the cached (ie already generated) jsp until the list has changed ( via a flush cache call somewhere else in application)

Wrapping code on the jsp layer, with an cache tag as follows:

<cache:cache key="foobar" scope="session">
  <%= myBean.getData() %>
</cache:cache>

means the java code myBean.getData() will only be called once per session (unless otherwise flushed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM