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();

posted on 2018-12-28 13:35  我是司  阅读(3456)  评论(0编辑  收藏  举报

导航