zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    rsync 配置
    DNS主从服务,子域授权,view视图,日志系统,压力测试
    ubuntu VNC server 黑屏 yum源更新(ubuntu16.04)
    HTTPD服务 openssl的https服务机制
    vmware Esxi 更换管理网卡IP
    httpd 虚拟主机建立之访问机制及其日志定义
    pxe kickstart 配置+TFTP+NFS多版本系统部署
    Linux nohup不输出日志文件的方法
    Tomcat部署时war和war exploded区别
    vim编辑超大文件
  • 原文地址:https://www.cnblogs.com/chinaifae/p/10190045.html
Copyright © 2011-2022 走看看