hello world example for ehcache?

前端 未结 2 1615
后悔当初
后悔当初 2020-12-24 05:56

ehcache is a hugely configurable beast, and the examples are fairly complex, often involving many layers of interfaces.

Has anyone come across the simplest example w

相关标签:
2条回答
  • 2020-12-24 06:27

    A working implementation of jbrookover's answer:

    import net.sf.ehcache.CacheManager;
    import net.sf.ehcache.Element;
    import net.sf.ehcache.Cache;
    
    public class EHCacheDemo  {
        public static final void main(String[] igno_red)  {
            CacheManager cchm = CacheManager.getInstance();
    
            //Create a cache
            cchm.addCache("test");
    
            //Add key-value pairs
            Cache cch = cchm.getCache("test");
            cch.put(new Element("tarzan", "Jane"));
            cch.put(new Element("kermit", "Piggy"));
    
            //Retrieve a value for a given key
            Element elt = cch.get("tarzan");
            String sPartner = (elt == null ? null : elt.getObjectValue().toString());
    
            System.out.println(sPartner);  //Outputs "Jane"
    
            //Required or the application will hang
            cchm.removeAllCaches();  //alternatively: cchm.shutdown();
        }
    }
    
    0 讨论(0)
  • 2020-12-24 06:28

    EhCache comes with a failsafe configuration that has some reasonable expiration time (120 seconds). This is sufficient to get it up and running.

    Imports:

    import net.sf.ehcache.CacheManager;
    import net.sf.ehcache.Element;
    

    Then, creating a cache is pretty simple:

    CacheManager.getInstance().addCache("test");
    

    This creates a cache called test. You can have many different, separate caches all managed by the same CacheManager. Adding (key, value) pairs to this cache is as simple as:

    CacheManager.getInstance().getCache("test").put(new Element(key, value));
    

    Retrieving a value for a given key is as simple as:

    Element elt = CacheManager.getInstance().getCache("test").get(key);
    return (elt == null ? null : elt.getObjectValue());
    

    If you attempt to access an element after the default 120 second expiration period, the cache will return null (hence the check to see if elt is null). You can adjust the expiration period by creating your own ehcache.xml file - the documentation for that is decent on the ehcache site.

    0 讨论(0)
提交回复
热议问题