简体   繁体   中英

How to implement java web application properties caching?

I have simple web application built with servlets 3.0 and Ajax, no freamwork is being used.

The application renders GUI components from DB. In order to avoid cases where DB failure causes the application to not work I'm considering using kind of caching that will serve the requests instead of accessing DB for every HTTP GET request and if the property requested is not available in that cache then fetch from DB, add to cache and serve request.

I was reading about properties files and in-memory cache implementations then run into statless beans and session beans and got confused. So what is the way to achieve this?

PS: Prefer not to use any freamwork.

I'm afraid you are mixing concepts here....

Properties files are plain text files containing key-value-pairs to store configuration and read them during runtime. They have little in common with your problem.

Stateless and statefull beans are again something different. A statefull bean may have an internal state. That is two calls to the same method may yield different results even though the context (db-contents etc) did not change.

So what is the way to achieve caching? There is not built-in utility to cache DB-requests. The most simple (but as well naive) approach would be something like

private final Map<String, String> componentCache = new HashMap<>();

public String getComponentMarkup(String componentId, String... parameters){
    //Build a key for the parameters. Maybe simple stringconcatenation.
    String key=buildKey(componentId, parameters); 
    if (!componentCache.containsKey(key)){
        //Delegate the call to the "old" method which queries the database.
        String component = getComponentMarkupFromDb(componentId,parameters); 
        componentCache.put(key, component);
    }
    return componentCache.get(key);
}

But the bottom line is you should think about why you want to implement the cache by yourself. There are tons of well tested solutions for you problem ( spring , hazelcast , etc ...). Your question indicates a not invented here syndrom ...

There are a few ways to do it depending what you want to do:

  • Cache web requests in the web tier using a servlet filter.
  • Cache SQL requests in the database access tier

A web cache will allow you cache requests based on URL pattern and requests parameters and trivial to do using Cacheonix web cache. The benefit of caching in the web tier is that the application doesn't have to spend time waiting for the database and rendering the response.

Caching SQL requests is a bit more involved but the benefit is that you have a fine-grained control of what queries go do the database and what ResultSets are cached.

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