zoukankan      html  css  js  c++  java
  • Spring整合EhCache详解

    一、EhCache介绍

    EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开 源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

    优点: 
    1. 快速 

    2. 简单 

    3. 多种缓存策略 

    4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 

    5. 缓存数据会在虚拟机重启的过程中写入磁盘 

    6. 可以通过RMI、可插入API等方式进行分布式缓存 

    7. 具有缓存和缓存管理器的侦听接口 

    8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 

    9. 提供Hibernate的缓存实现

    缺点: 
    1. 使用磁盘Cache的时候非常占用磁盘空间:这是因为DiskCache的算法简单,该算法简单也导致Cache的效率非常高。它只是对元素直接追加存储。因此搜索元素的时候非常的快。如果使用DiskCache的,在很频繁的应用中,很快磁盘会满。 

    2. 不能保证数据的安全:当突然kill掉java的时候,可能会产生冲突,EhCache的解决方法是如果文件冲突了,则重建cache。这对于Cache 数据需要保存的时候可能不利。当然,Cache只是简单的加速,而不能保证数据的安全。如果想保证数据的存储安全,可以使用Bekeley DB Java Edition版本。这是个嵌入式数据库。可以确保存储安全和空间的利用率。

    ehcache 和 redis 比较:

    1. ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。

    2. redis是通过socket访问到缓存服务,效率比ecache低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用ehcache。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用redis。

    3. ehcache也有缓存共享方案,不过是通过RMI或者Jgroup多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适。

    二、整合详解

    环境:idea + maven + spring + ehcache + junit

    1、添加相关依赖(pom.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <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>top.jimc</groupId>
        <artifactId>spring-ehcache-test</artifactId>
        <version>1.0-SNAPSHOT</version>
        <description>Spring整合Ehcache测试项目</description>
    
        <properties>
            <junit.version>4.12</junit.version>
            <spring.version>4.2.5.RELEASE</spring.version>
            <aspectj.version>1.8.8</aspectj.version>
            <ehcache.version>2.8.2</ehcache.version>
            <log4j.version>1.2.17</log4j.version>
            <slf4j.version>1.6.6</slf4j.version>
        </properties>
    
        <dependencies>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
    
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--对AspectJ支持,面向切面编程,需要外部依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- AspectJ -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
    
            <!-- ehcache -->
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
                <version>${ehcache.version}</version>
            </dependency>
    
            <!-- 日志工具 -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
        </dependencies>
    </project>
    View Code

    2、添加ehcache配置文件ehcache.xml

    默认情况下Ehcache会自动加载classpath根目录下名为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">
    
        <!-- 磁盘缓存位置:当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
        <diskStore path="java.io.tmpdir"/>
    
        <!-- 设定缓存的默认数据过期策略 -->
        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                overflowToDisk="true"
                timeToIdleSeconds="10"
                timeToLiveSeconds="20"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120" />
    
        <!-- 10秒过期,只能缓存20秒 -->
        <cache name="cacheTest"
               maxElementsInMemory="1000"
               eternal="false"
               timeToIdleSeconds="10"
               timeToLiveSeconds="20"
               overflowToDisk="true" />
    
        <!-- 缓存半小时 -->
        <cache name="halfHour"
               maxElementsInMemory="10000"
               maxElementsOnDisk="100000"
               eternal="false"
               timeToIdleSeconds="1800"
               timeToLiveSeconds="1800"
               overflowToDisk="true"
               diskPersistent="false" />
    
        <!-- 缓存一小时 -->
        <cache name="oneHour"
               maxElementsInMemory="10000"
               maxElementsOnDisk="100000"
               eternal="false"
               timeToIdleSeconds="3600"
               timeToLiveSeconds="3600"
               overflowToDisk="true"
               diskPersistent="false" />
    
        <!-- 缓存一天 -->
        <cache name="oneDay"
               maxElementsInMemory="10000"
               maxElementsOnDisk="100000"
               eternal="false"
               timeToIdleSeconds="86400"
               timeToLiveSeconds="86400"
               overflowToDisk="true"
               diskPersistent="false" />
    
    </ehcache>
    View Code

    cache元素属性说明:

    name:缓存名称

    maxElementsInMemory:内存中最大缓存对象数

    maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大

    eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false

    overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。

    diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。

    diskPersistent:是否缓存虚拟机重启期数据,是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名 为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把 cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。

    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒。

    timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性 值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限 期地处于空闲状态。

    timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有 效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。

    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。

    3、添加spring配置文件application.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                               http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd
                               http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    
        <context:component-scan base-package="top.jimc.ehcache.service"/>
    
        <!-- Spring提供的基于的Ehcache实现的缓存管理器 -->
        <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
            <property name="configLocation" value="classpath:ehcache.xml"/>
        </bean>
    
        <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
            <property name="cacheManager" ref="ehcacheManager"/>
        </bean>
    
        <!-- cache注解 -->
        <cache:annotation-driven cache-manager="springCacheManager"/>
    
    </beans>
    View Code

    4、创建EhcacheService接口

    package top.jimc.ehcache.service;
    
    import top.jimc.ehcache.po.User;
    
    /**
     * @author Jimc.
     * @since 2018/9/21.
     */
    public interface EhcacheService {
    
        String getTimestamp(String param);
    
        String getDataFromDB(String key);
    
        void removeDataAtDB(String key);
    
        String refreshData(String key);
    
    
        User findUserById(String userId);
    
        void removeUserById(String userId);
    
        void removeAllUser();
    
    }
    View Code

    5、创建EhcacheServiceImpl实现类

    package top.jimc.ehcache.service.impl;
    
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    import top.jimc.ehcache.po.User;
    import top.jimc.ehcache.service.EhcacheService;
    
    /**
     * @author Jimc.
     * @since 2018/9/21.
     */
    @Service
    public class EhcacheServiceImpl implements EhcacheService {
    
        @Cacheable(value = "cacheTest", key = "#param")
        public String getTimestamp(String param) {
            return String.valueOf(System.currentTimeMillis());
        }
    
        @Cacheable(value = "cacheTest", key = "#key")
        public String getDataFromDB(String key) {
            System.out.println("模拟从数据库中获取数据...");
            return key + ":" + String.valueOf(Math.round(Math.random()*1000000));
        }
    
        @CacheEvict(value = "cacheTest", key = "#key")
        public void removeDataAtDB(String key) {
            System.out.println("模拟从数据库中删除数据...");
        }
    
        @CachePut(value = "cacheTest", key = "#key")
        public String refreshData(String key) {
            System.out.println("模拟从数据库中加载数据...");
            return key + "::" + String.valueOf(Math.round(Math.random()*1000000));
        }
    
    
    
        @Cacheable(value = "cacheTest", key = "'user:' + #userId")
        public User findUserById(String userId) {
            System.out.println("模拟从数据库中查询数据");
            return new User(userId, "Tom");
        }
    
        /**
         * 清除cacheTest中指定key的缓存
         */
        @CacheEvict(value = "cacheTest", key = "'user:' + #userId")
        public void removeUserById(String userId) {
            System.out.println("cacheTest remove:" + userId);
        }
    
        /**
         * 清除cacheTest中全部缓存
         */
        @CacheEvict(value = "cacheTest", allEntries = true)
        public void removeAllUser() {
            System.out.println("cacheTest remove all");
        }
    }
    View Code

    6、创建spring单元测试基类BaseJunit4Test

    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * 测试基类
     * @author Jimc.
     * @since 2018/9/21.
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class BaseJunit4Test {
    }
    View Code

    7、创建测试类EhcacheServiceTest

    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import top.jimc.ehcache.service.EhcacheService;
    
    /**
     * @author Jimc.
     * @since 2018/9/21.
     */
    public class EhcacheServiceTest extends BaseJunit4Test {
    
        @Autowired
        private EhcacheService ehcacheService;
    
        @Test
        public void testTimestamp() throws InterruptedException {
            System.out.println("第一次调用:" + ehcacheService.getTimestamp("param"));
            Thread.sleep(4000);
            System.out.println("再过4秒之后调用:" + ehcacheService.getTimestamp("param"));
            Thread.sleep(11000);
            System.out.println("再过11秒之后调用:" + ehcacheService.getTimestamp("param"));
        }
    
        @Test
        public void testDataCache() {
            String key = "LiSi";
            String value = ehcacheService.getDataFromDB(key);// 模拟从数据库中获取数据
            System.out.println(value);
            value = ehcacheService.getDataFromDB(key);// 从缓存中获取数据,所以不执行该方法体
            System.out.println(value);
            ehcacheService.removeDataAtDB(key);// 从数据库中删除数据
            value = ehcacheService.getDataFromDB(key);  // 再次从数据库中获取数据(缓存数据删除了,所以要重新获取,执行方法体)
            System.out.println(value);
        }
    
        @Test
        public void testDataPut() {
            String key = "WangWu";
            String value = ehcacheService.refreshData(key);// 模拟从数据库中加载数据
            System.out.println(value);
            value = ehcacheService.getDataFromDB(key);// 从缓存中获取数据,所以不执行该方法体
            System.out.println(value);
    
            value = ehcacheService.refreshData(key);// 再次模拟从数据库中加载数据,此时会执行方法体
            System.out.println(value);
            value = ehcacheService.getDataFromDB(key);// 从缓存中获取数据,所以不执行该方法体
            System.out.println(value);
    
        }
    
    
        @Test
        public void testFindById(){
            System.out.println(ehcacheService.findUserById("1"));// 先模拟从数据库中查询数据
            System.out.println(ehcacheService.findUserById("1"));// 从缓存中取数据,不会执行方法体
        }
    
        @Test
        public void testRemoveUserById(){
            System.out.println(ehcacheService.findUserById("1"));// 先添加到缓存
    
            ehcacheService.removeUserById("1");// 再删除
    
            System.out.println(ehcacheService.findUserById("1")); // 再查询,如果不存在会执行方法体
        }
    
        @Test
        public void testRemoveAllUser(){
            // 先模拟从数据库中查询数据
            System.out.println(ehcacheService.findUserById("1"));
            System.out.println(ehcacheService.findUserById("2"));
    
            ehcacheService.removeAllUser();// 清除cacheTest中全部缓存
    
            // 重新模拟从数据库中查询数据,此时执行了方法体,证明缓存中的数据已被清除
            System.out.println(ehcacheService.findUserById("1"));
            System.out.println(ehcacheService.findUserById("2"));
        }
    
    }
    View Code

    8、执行结果

    testTimestamp()执行结果:
    第一次调用:1537515009017
    再过4秒之后调用:1537515009017
    再过11秒之后调用:1537515024027
    
    testDataCache()执行结果:
    模拟从数据库中获取数据...
    LiSi:477475
    LiSi:477475
    模拟从数据库中删除数据...
    模拟从数据库中获取数据...
    LiSi:308969
    
    testDataPut()执行结果:
    模拟从数据库中加载数据...
    WangWu::77005
    WangWu::77005
    模拟从数据库中加载数据...
    WangWu::539514
    WangWu::539514
    
    testFindById()执行结果:
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@6736fa8d
    top.jimc.ehcache.po.User@6736fa8d
    
    testRemoveUserById()执行结果:
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@6736fa8d
    cacheTest remove:1
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@50313382
    
    testRemoveAllUser()执行结果:
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@6736fa8d
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@52815fa3
    cacheTest remove all
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@1cb346ea
    模拟从数据库中查询数据
    top.jimc.ehcache.po.User@4c012563
    View Code

    9、注解基本使用详解

    Spring对缓存的支持类似于对事务的支持。 
    首先使用注解标记方法,相当于定义了切点,然后使用Aop技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。

    (1)@Cacheable

    表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。 
    这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。 
    可以使用key属性来指定key的生成规则。

    参数:

    • alue:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name, 指明将值缓存到哪个Cache中
    • key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL,如果要引用参数值使用井号加参数名,如:#userId,一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值 , 本例子中使用实体加冒号再加ID组合成键的名称,如”user:1”、”order:223123”等
    • condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL

    (2)@CachePut

    与@Cacheable不同,@CachePut不仅会缓存方法的结果,还会执行方法的代码段。它支持的属性和用法都与@Cacheable一致。

    (3)@CacheEvict

    与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据。

    参数:

    • value:缓存位置名称,不能为空,同上
    • key:缓存的key,默认为空,同上
    • condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
    • allEntries:true表示清除value中的全部缓存,默认为false

     三、示例源码下载

    spring-ehcache-test

  • 相关阅读:
    为什么要设计好目录结构?
    python 程序退出方式
    mysql超出最大连接数解决方法
    服务器网络连接状态
    Python判断文件是否存在的三种方法【转】
    Nginx日志中的金矿 -- 好文收藏
    vsphere中的linux虚拟机安装vmware-tools
    vsphere中的vcenter创建esxi模板虚拟机新建无法连接网络
    linux同步系统时间
    Linux内核中TCP SACK机制远程DoS预警通告
  • 原文地址:https://www.cnblogs.com/Jimc/p/9685350.html
Copyright © 2011-2022 走看看