首页 > 代码库 > ehcache2.8.3入门示例:hello world

ehcache2.8.3入门示例:hello world

一、pom.xml 依赖项

 1         <dependency> 2             <groupId>net.sf.ehcache</groupId> 3             <artifactId>ehcache</artifactId> 4             <version>2.8.3</version> 5         </dependency> 6  7         <dependency> 8             <groupId>org.slf4j</groupId> 9             <artifactId>slf4j-api</artifactId>10             <version>1.7.7</version>11         </dependency>

 

二、ehcache.xml

 1 <?xml version="1.0" encoding="UTF-8"?> 2  3 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" 5     monitoring="autodetect" dynamicConfig="true"> 6  7  8     <diskStore path="java.io.tmpdir" /> 9 10     <defaultCache maxEntriesLocalHeap="10000" eternal="false"11         timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"12         maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"13         memoryStoreEvictionPolicy="LRU">14         <persistence strategy="localTempSwap" />15     </defaultCache>16 17     <cache name="sampleCache1" maxEntriesLocalHeap="10000"18         maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20"19         timeToIdleSeconds="300" timeToLiveSeconds="600"20         memoryStoreEvictionPolicy="LFU" transactionalMode="off">21         <persistence strategy="localTempSwap" />22     </cache>23 24     <cache name="sampleCache2" maxEntriesLocalHeap="1000" eternal="true"25         memoryStoreEvictionPolicy="FIFO" />26 27 </ehcache> 

 

三、示例代码

 1 package cnblogs.ehcache; 2  3 import net.sf.ehcache.Cache; 4 import net.sf.ehcache.CacheManager; 5 import net.sf.ehcache.Element; 6  7 public class App { 8     public static void main(String[] args) throws InterruptedException { 9         CacheManager manager = CacheManager.create();10 11         // 取出所有的cacheName12         String names[] = manager.getCacheNames();13         System.out.println("----all cache names----");14         for (int i = 0; i < names.length; i++) {15             System.out.println(names[i]);16         }17 18         System.out.println("----------------------");19         // 得到一个cache对象20         Cache cache1 = manager.getCache(names[0]);21 22         // 向cache1对象里添加缓存23         cache1.put(new Element("key1", "values1"));24         Element element = cache1.get("key1");25 26         // 读取缓存27         System.out.println("key1 \t= " + element.getObjectValue());28 29         // 手动创建一个cache(ehcache里必须有defaultCache存在,"test"可以换成任何值)30         Cache cache2 = new Cache("test", 1, true, false, 2, 3);31         manager.addCache(cache2);32 33         cache2.put(new Element("jimmy", "菩提树下的杨过"));34 35         // 故意停1.5秒,以验证是否过期36         Thread.sleep(1500);37 38         Element eleJimmy = cache2.get("jimmy");39 40         //1.5s < 2s 不会过期41         if (eleJimmy != null) {42             System.out.println("jimmy \t= " + eleJimmy.getObjectValue());43         }44 45         //再等上0.5s, 总时长:1.5 + 0.5 >= min(2,3),过期46         Thread.sleep(500);47 48         eleJimmy = cache2.get("jimmy");49 50         if (eleJimmy != null) {51             System.out.println("jimmy \t= " + eleJimmy.getObjectValue());52         }53 54         // 取出一个不存在的缓存项55         System.out.println("fake \t= " + cache2.get("fake"));56 57         manager.shutdown();58     }59 60 }

运行结果:

----all cache names----
sampleCache2
sampleCache1
----------------------
key1     = values1
jimmy     = 菩提树下的杨过
fake     = null

 

四、关于timeToLiveSeconds、timeToIdleSeconds

直接看net.sf.ehcache.Element源码的片段:

  1      /**  2      * The amount of time for the element to live, in seconds. 0 indicates unlimited.  3      */  4     private volatile int timeToLive = Integer.MIN_VALUE;  5   6     /**  7      * The amount of time for the element to idle, in seconds. 0 indicates unlimited.  8      */  9     private volatile int timeToIdle = Integer.MIN_VALUE; 10      11      12     /** 13      * Sets time to Live 14      * <P/> 15      * Value must be a positive integer, 0 means infinite time to live. 16      * <P/> 17      * If calling this method with 0 as the parameter, consider using {@link #setEternal(boolean)} 18      * or make sure you also explicitly call {@link #setTimeToIdle(int)}. 19      * 20      * @param timeToLiveSeconds the number of seconds to live 21      */ 22     public void setTimeToLive(final int timeToLiveSeconds) { 23         if (timeToLiveSeconds < 0) { 24             throw new IllegalArgumentException("timeToLive can‘t be negative"); 25         } 26         this.cacheDefaultLifespan = false; 27         this.timeToLive = timeToLiveSeconds; 28     } 29  30     /** 31      * Sets time to idle 32      * <P/> 33      * Value must be a positive integer, 0 means infinite time to idle. 34      * <P/> 35      * If calling this method with 0 as the parameter, consider using {@link #setEternal(boolean)} 36      * or make sure you also explicitly call {@link #setTimeToLive(int)}. 37      * 38      * @param timeToIdleSeconds the number of seconds to idle 39      */ 40     public void setTimeToIdle(final int timeToIdleSeconds) { 41         if (timeToIdleSeconds < 0) { 42             throw new IllegalArgumentException("timeToIdle can‘t be negative"); 43         } 44         this.cacheDefaultLifespan = false; 45         this.timeToIdle = timeToIdleSeconds; 46     } 47      48      49  50     /** 51      * An element is expired if the expiration time as given by {@link #getExpirationTime()} is in the past. 52      * 53      * @return true if the Element is expired, otherwise false. If no lifespan has been set for the Element it is 54      *         considered not able to expire. 55      * @see #getExpirationTime() 56      */ 57     public boolean isExpired() { 58         if (!isLifespanSet() || isEternal()) { 59             return false; 60         } 61  62         long now = System.currentTimeMillis(); 63         long expirationTime = getExpirationTime(); 64  65         return now > expirationTime; 66     } 67      68      69     /** 70      * An element is expired if the expiration time as given by {@link #getExpirationTime()} is in the past. 71      * <p> 72      * This method in addition propogates the default TTI/TTL values of the supplied cache into this element. 73      * 74      * @param config config to take default parameters from 75      * @return true if the Element is expired, otherwise false. If no lifespan has been set for the Element it is 76      *         considered not able to expire. 77      * @see #getExpirationTime() 78      */ 79     public boolean isExpired(CacheConfiguration config) { 80         if (cacheDefaultLifespan) { 81             if (config.isEternal()) { 82                 timeToIdle = 0; 83                 timeToLive = 0; 84             } else { 85                 timeToIdle = TimeUtil.convertTimeToInt(config.getTimeToIdleSeconds()); 86                 timeToLive = TimeUtil.convertTimeToInt(config.getTimeToLiveSeconds()); 87             } 88         } 89         return isExpired(); 90     } 91  92     /** 93      * Returns the expiration time based on time to live. If this element also has a time to idle setting, the expiry 94      * time will vary depending on whether the element is accessed. 95      * 96      * @return the time to expiration 97      */ 98     public long getExpirationTime() { 99         if (!isLifespanSet() || isEternal()) {100             return Long.MAX_VALUE;101         }102 103         long expirationTime = 0;104         long ttlExpiry = creationTime + TimeUtil.toMillis(getTimeToLive());105 106         long mostRecentTime = Math.max(creationTime, lastAccessTime);107         long ttiExpiry = mostRecentTime + TimeUtil.toMillis(getTimeToIdle());108 109         if (getTimeToLive() != 0 && (getTimeToIdle() == 0 || lastAccessTime == 0)) {110             expirationTime = ttlExpiry;111         } else if (getTimeToLive() == 0) {112             expirationTime = ttiExpiry;113         } else {114             expirationTime = Math.min(ttlExpiry, ttiExpiry);115         }116         return expirationTime;117     }118 119     /**120      * @return true if the element is eternal121      */122     public boolean isEternal() {123         return (0 == timeToIdle) && (0 == timeToLive);124     }125     126     127     /**128      * Sets whether the element is eternal.129      *130      * @param eternal131      */132     public void setEternal(final boolean eternal) {133         if (eternal) {134             this.cacheDefaultLifespan = false;135             this.timeToIdle = 0;136             this.timeToLive = 0;137         } else if (isEternal()) {138             this.cacheDefaultLifespan = false;139             this.timeToIdle = Integer.MIN_VALUE;140             this.timeToLive = Integer.MIN_VALUE;141         }142     }143 144     /**145      * Whether any combination of eternal, TTL or TTI has been set.146      *147      * @return true if set.148      */149     public boolean isLifespanSet() {150         return this.timeToIdle != Integer.MIN_VALUE || this.timeToLive != Integer.MIN_VALUE;151     }152 153     /**154      * @return the time to live, in seconds155      */156     public int getTimeToLive() {157         if (Integer.MIN_VALUE =http://www.mamicode.com/= timeToLive) {158             return 0;159         } else {160             return timeToLive;161         }162     }163 164     /**165      * @return the time to idle, in seconds166      */167     public int getTimeToIdle() {168         if (Integer.MIN_VALUE =http://www.mamicode.com/= timeToIdle) {169             return 0;170         } else {171             return timeToIdle;172         }173     }174     175     176     /**177      * Set the default parameters of this element - those from its enclosing cache.178      * @param tti TTI in seconds179      * @param ttl TTL in seconds180      * @param eternal <code>true</code> if the element is eternal.181      */182     protected void setLifespanDefaults(int tti, int ttl, boolean eternal) {183         if (eternal) {184             this.timeToIdle = 0;185             this.timeToLive = 0;186         } else if (isEternal()) {187             this.timeToIdle = Integer.MIN_VALUE;188             this.timeToLive = Integer.MIN_VALUE;189         } else {190             timeToIdle = tti;191             timeToLive = ttl;192         }193     }