Java缓存框架---EhCache(基于Maven+Spring的EhCache入门教程)

在当今大数据爆发时代,数据量每天都呈“爆炸式”增长,频繁的数据库访问无疑给数据库带来的极大负载,除了增大物理服务器的数量,我们也可以将一些常用的、公共的资源以cache形式放在客户端或者靠近客户端的服务器上,从而减少了服务器的负载,进一步也改善了系统的整体性能。今天就介绍一款常用的缓存框架---EhCache。

什么是EhCache?

ehcache是现在最流行的纯java开源框架,配置简单,结构清晰,功能强大,最初知道它,是从hibernate的缓存开始的。网上中文的ehcache材料以简单的介绍和配置方法居多,如果你有这方面的问题,请自行看官网api文档,但是很少见到特性说明和对实现原理的分析,因此在这这篇文章里面,我会详细介绍和分析ehcache的特性,加上一些自己的理解和思考,希望对缓存感兴趣的朋友有所收获。

EhCache入门教程

  1. 新建一个maven项目
  2. 在maven项目的pom.xml文件中添加对EhCache及Spring的依赖,如下所示:

     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>    
     <groupId>com.imooc</groupId>
     <artifactId>Ehcache</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <packaging>jar</packaging>   
     <name>Ehcache</name>
     <url>http://maven.apache.org</url>  
     <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <junit.version>4.10</junit.version>
       <spring.version>4.2.3.RELEASE</spring.version>
     </properties>
     <dependencies>
         <!-- ehcache jar package -->
         <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache</artifactId>
           <version>2.10.2</version>
       </dependency>
       <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>${junit.version}</version>
         <scope>test</scope>
       </dependency>
    
       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
    
    
       <!-- springframework -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context-support</artifactId>
           <version>${spring.version}</version>
       </dependency>
     </dependencies>
     <repositories>
       <repository>
           <id>aliyun</id>
           <name>aliyun</name>
           <url>http://maven.aliyun.com/nexus/content/groups/public</url>
       </repository>
     </repositories>

    </project>

  3. 在src/main/resources目录下创建ehcache的配置文件ehcache.xml,如下:

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

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

            xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">      
     <!-- 磁盘缓存位置 -->  
     <diskStore path="E:/file"/>       
     <!-- 默认缓存 -->  
     <defaultCache  
             maxEntriesLocalHeap="10000"  
             eternal="false"  
             timeToIdleSeconds="120"  
             timeToLiveSeconds="120"  
             maxEntriesLocalDisk="10000000"  
             diskExpiryThreadIntervalSeconds="120"  
             memoryStoreEvictionPolicy="LRU"/>       
     <!-- helloworld1缓存 -->  
     <cache name="helloworld1"  
            maxElementsInMemory="1"  
            eternal="false"  
            timeToIdleSeconds="5"  
            timeToLiveSeconds="5"  
            overflowToDisk="true"  
            memoryStoreEvictionPolicy="LRU"/>                
            <!-- helloworld2缓存 -->  
     <cache name="helloworld2"  
            maxElementsInMemory="1000"  
            eternal="false"  
            timeToIdleSeconds="5"  
            timeToLiveSeconds="5"  
            overflowToDisk="false"  
            memoryStoreEvictionPolicy="LRU"/>               

    </ehcache>

  4. 针对ehcache的配置文件的参数进行详细说明:
    diskStore : ehcache支持内存和磁盘两种存储

    • path :指定磁盘存储的位置

默认cache参数配置说明:
defaultCache : 默认的缓存

* maxEntriesLocalHeap=”10000”
    * eternal=”false”
    * timeToIdleSeconds=”120”
    * timeToLiveSeconds=”120”
    * maxEntriesLocalDisk=”10000000”
    * diskExpiryThreadIntervalSeconds=”120”
    * memoryStoreEvictionPolicy=”LRU”

cache :自定的缓存,当自定的配置不满足实际情况时可以通过自定义(可以包含多个cache节点)

* name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象
* maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个
* clearOnFlush:内存数量最大时是否清除。
* eternal :设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时
* timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
* timeToLiveSeconds :缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
* overflowToDisk :内存不足时,是否启用磁盘缓存。
* maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
* maxElementsOnDisk:硬盘最大缓存个数。
* diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
* diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。
* diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。

ehcache缓存的3种清空策略:
1 FIFO,先进先出
2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

  1. 编辑代码测试Ehcache

    package com.imooc.Ehcache;

    import java.io.InputStream;
    import net.sf.ehcache.Cache;
    import net.sf.ehcache.CacheManager;
    import net.sf.ehcache.Element;
    /**

    * 通过配置文件(ehcache.xml)来使用缓存 
    * @author Administrator 
 */  
public class EhCache2 {        
    public static void main(String[] args) {  
         //通过读取ehcache配置文件来创建缓存管理器即CacheManager  
        InputStream in = EhCache2.class.getClassLoader().getResourceAsStream("ehcache1.xml");
        CacheManager cacheManager = CacheManager.create(in);  
  
        // 创建一个缓存实例(在配置文件中获取一个缓存实例)  
        final Cache cache = cacheManager.getCache("helloworld1");  
        
        final String key = "greeting";  
        final String key1 = "greeting1";
        //创建一个数据容器来存放我们所创建的element  
        final Element putGreeting = new Element(key, "Hello, World!");  
        final Element putGreeting1 = new Element(key1, "Hello Ehcache");
        
        //将数据放入到缓存实例中  
        cache.put(putGreeting);  
        cache.put(putGreeting1);
        
        //取值  
        final Cache cache2 = cacheManager.getCache("helloworld1");  
        final Element getGreeting = cache2.get(key); 
        final Element getGreeting1 = cache2.get(key1);
  
        // Print the value  
        System.out.println("value======//========"+getGreeting.getObjectValue());  
        System.out.println("value1=====//========"+getGreeting1.getObjectKey());
    }       
}  
  1. 结果验证,如果后台输出如下字段即在指定的cache存放文件夹找到创建的cache就说明我们打开了学习EhCache大门。

后台输出: value======//========Hello, World!

          value1=====//========greeting1
  1. 最后附上本次实例的源码:
    链接:https://pan.baidu.com/s/1nu6rrz7 密码:p5vw
    Ehcache官方文档下载链接:链接:https://pan.baidu.com/s/1cyg3Tk 密码:0zf0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值