码上敲享录 > java入门知识分享 > java项目中ehcache缓存最简单用法

java项目中ehcache缓存最简单用法

上一章章节目录下一章 2017-11-01已有2196人阅读 评论(0)

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

本文地址:http://yayihouse.com/yayishuwu/chapter/1014


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交