java項目中ehcache緩存最簡單用法


 

 

java項目中ehcache緩存最簡單用法:

 

1.下載ehcache-core-2.4.3.jar復制到項目的lib目錄下

2.新建ehcache.xml文件,放置在項目src目錄下的resource目錄下。ehcache.xml內容如下:

<?xml version="1.0" encoding="UTF-8"?>

<ehcache updateCheck="false">

<diskStore path="java.io.tmpdir" />

<cache name="dictCache" maxElementsInMemory="500" overflowToDisk="true"

eternal="true">

<cacheEventListenerFactory

class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"

properties="replicatePuts=false,replicateUpdatesViaCopy=false" />

</cache>

<defaultCache maxElementsInMemory="10000" overflowToDisk="true"

eternal="false" memoryStoreEvictionPolicy="LRU" maxElementsOnDisk="10000000"

diskExpiryThreadIntervalSeconds="600" timeToIdleSeconds="3600"

timeToLiveSeconds="100000" diskPersistent="false" />

</ehcache>

 

3.在項目啟動的時候加載ehcache.xml文件。新建一個工具類TableCache.lava。在項目啟動的時候調用:TableCache.getInstance();即可加載ehcache.xml

public class TableCache {  

   private static final String path = "resource/ehcache.xml";  

   private static URL url;  

   private static CacheManager manager;  

   private static TableCache ehCache;  

   private TableCache(String path) {  

       url = getClass().getResource(path);  

       manager = CacheManager.create(url);  

   }  

   public static TableCache getInstance() {  

       if (ehCache== null) {  

           ehCache= new TableCache(path);  

       }  

       return ehCache;  

   }

}

 

4.使用方法:

4.1在ehcache.xml中聲明了一個名字為dictCache的緩存,在java代碼中獲取它

  Cache ehCache== CacheManager.getInstance().getCache("dictCache");

4.2 把對象存入到緩存中

  Element element = new Element("str", "我是誰");//str是鍵,可以通過鍵獲取值"我是誰"

  ehCache.put(element);

4.3獲取緩存中的值

  Element element = ehCache.get("str");

  String str= (String)element.getObjectValue();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM