ehcache 简单例子

来源:互联网 发布:知乎 电脑版 编辑:程序博客网 时间:2024/05/21 18:36

ehcache-缓存

缓存机制使用前提:

如果有一个资源在系统中被用到的频率太多的时候,建议使用缓存机制。简单说就是 80%的时间在使用20%的资源,那么这些资源就应该使用缓存了。

缓存的必要性:

因为JVM本身自带缓存有限,而且使用自己做的简单缓存(比如一个Map)虽然比较简单,但是缓存数据量有一定要求(比如数据量太大的话,JVM就不用干别的了)

所以这个时候会选择第三方插件缓存机制,比如ehcache、redis等。

需要的jar:

ehcache-1.7.0.jar   可以在网上拔下来。或者搜索ehcache,下载jar包

配置文件:

<ehcache xmlns:xsi="<a target=_blank href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xsi:noNamespaceSchemaLocation="ehcache.xsd">  <diskStore path="java.io.tmpdir"/>  <defaultCache    maxElementsInMemory="5000000"    eternal="true"    timeToIdleSeconds="0"    timeToLiveSeconds="0"    overflowToDisk="false"    diskSpoolBufferSizeMB="300"    maxElementsOnDisk="0"    diskPersistent="false"    memoryStoreEvictionPolicy="LRU">  </defaultCache>   <cache name="testCache"      maxElementsInMemory="1000000"      maxElementsOnDisk="0"      eternal="false"      overflowToDisk="false"      diskPersistent="false"      timeToIdleSeconds="0"      timeToLiveSeconds="0"      diskSpoolBufferSizeMB="300"      diskExpiryThreadIntervalSeconds="120"      memoryStoreEvictionPolicy="FIFO"      />  </ehcache>

配置文件说明:

name:缓存的唯一标示。defaultCache是默认缓存,可以不填。如果不指定缓存,那么都会从默认缓存中取资源。如果只需要一个缓存,可以只配置一个defaultCache
maxElementsInMemory:内存中保持的对象数量。
maxElementsOnDisk:DiskStore中保持的对象数量,默认值为0,表示不限制。
eternal:是否是永恒数据,如果是,则它的超时设置会被忽略。
overflowToDisk:如果内存中数据数量超过maxElementsInMemory限制,是否要缓存到磁盘上。
timeToIdleSeconds:对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
timeToLiveSeconds:对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
diskExpiryThreadIntervalSeconds:对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
diskSpoolBufferSizeMB:DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
memoryStoreEvictionPolicy:如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。

将配置好的ehcache.xml放到程序运行环境中,在初始化时被加载。

Java测试类:

因为ehcache中数据是以对象的形式存在的,使用了java的序列化保存到磁盘,所以保存的对象要实现Serializable接口。

javaBean类:

public class Test implements Serializable {       private static final long serialVersionUID = 1L;       public Long cuid;       public String name;          @Override      public String toString() {           return String.format("CUID:%s,,,NAME:%s", cuid, name);       }   }

获取缓存的方法:

CacheManager cacheManager = CacheManager.create("ehcache.xml");   Cache cache= cacheManager.getCache("alarmCache");  

添加数据到缓存:

public static void inputData() throws Exception {           CacheManager cacheManager = CacheManager.create("ehcache.xml");           cacheManager.addCache("testCache");           Cache testCache = manager.getCache("testCache");           //获取数据库连接         Class.forName(dbDriver);           Connection conn = DriverManager.getConnection(dbURL, user, pass);           try {                           Statement s = conn.createStatement();               String sql = "SELECT CUID,NAME FROM TEST";               ResultSet dataSet = s.executeQuery(sql);               for (int i = 1; dataSet .next(); i++) {                   Test test= new Test();                   test.cuid = dataSet .getLong(1);                   test.name = dataSet .getString(2);                                    testCache.put(new Element(test.cuid, test));               }                        } catch (Exception ex) {               ex.printStackTrace();           } finally {               conn.close();           }   } 

 

 


从缓存中获取数据:

public static void main(String[] args){          Demo.inputeData();          Cache test= manager.getCache("testCache");             Element e= test.get(new Long(cuid))          System.out.println(e.getValue());  }

 

注:如果 cacheManager.addCache("testCache");没有获得缓存(ehcache.xml没有配置名称为testCache的缓存),那么缓存机制会自动使用默认缓存 defaultCache为模板创建一个名称叫做testCache的缓存

其他:

ehcache的配置是支持磁盘持久化的。如果想要保证缓存里的对象即时的被输出到磁盘,可以调用cache.flush();

ehcache可以支持分布式缓存。


 

0 0