Java Web Application: How to implement caching techniques?

前端 未结 6 2034
别那么骄傲
别那么骄傲 2020-12-12 18:16

I am developing a Java web application that bases it behavior through large XML configuration files that are loaded from a web service. As these files are not actually requi

6条回答
  •  一整个雨季
    2020-12-12 18:50

    Here's an example of caching with EhCache. This code is used in several projects to implement ad hoc caching.

    1) Put your cache in the global context. (Don't forget to add the listener in WEB.XML).

    import net.sf.ehcache.Cache;
    import net.sf.ehcache.CacheManager;
    
    public class InitializationListener implements ServletContextListener {    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            ServletContext ctx = sce.getServletContext();
            CacheManager singletonManager = CacheManager.create();
            Cache memoryOnlyCache = new Cache("dbCache", 100, false, true, 86400,86400);
            singletonManager.addCache(memoryOnlyCache);
            cache = singletonManager.getCache("dbCache");       
            ctx.setAttribute("dbCache", cache );           
        }
    }
    

    2) Retrieve the cache instance when you need it. i.e. from a servlet:

    cache = (Cache) this.getContext().getAttribute("dbCache");

    3) Query the cache just before you do an expensive operation.

            Element e = getCache().get(key);
            if (e != null) {
                result = e.getObjectValue(); // get object from cache
            } else {
                // Write code to create the object you need to cache, then store it in the cache.
                Element resultCacheElement = new Element(key, result);
                cache.put(resultCacheElement);
    
            }
    

    4) Also don't forget to invalidate cached objects when appropriate.

    You can find more samples here

提交回复
热议问题