zoukankan      html  css  js  c++  java
  • Ehcache缓存实例

    一:目录

    • EhCache 简介
    • Hello World 示例
    • Spring 整合
    • Dummy CacheManager 的配置和作用

    二: 简介

    1. 基本介绍

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

    Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。

    2. 主要的特性有:

    1. 快速
    2. 简单
    3. 多种缓存策略
    4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
    5. 缓存数据会在虚拟机重启的过程中写入磁盘
    6. 可以通过RMI、可插入API等方式进行分布式缓存
    7. 具有缓存和缓存管理器的侦听接口
    8. 支持多缓存管理器实例,以及一个实例的多个缓存区域
    9. 提供Hibernate的缓存实现

    3. 集成

    可以单独使用,一般在第三方库中被用到的比较多(如mybatis、shiro等)ehcache 对分布式支持不够好,多个节点不能同步,通常和redis一块使用

    4. ehcache 和 redis 比较

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

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

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

    缓存命中率

    即从缓存中读取数据的次数 与 总读取次数的比率,命中率越高越好:

    命中率 = 从缓存中读取次数 / (总读取次数[从缓存中读取次数 + 从慢速设备上读取的次数])

    Miss率 = 没有从缓存中读取的次数 / (总读取次数[从缓存中读取次数 + 从慢速设备上读取的次数])

    这是一个非常重要的监控指标,如果做缓存一定要健康这个指标来看缓存是否工作良好;

    缓存策略

    Eviction policy

    移除策略,即如果缓存满了,从缓存中移除数据的策略;常见的有LFU、LRU、FIFO:

    FIFO(First In First Out):先进先出算法,即先放入缓存的先被移除;

    LRU(Least Recently Used):最久未使用算法,使用时间距离现在最久的那个被移除;

    LFU(Least Frequently Used):最近最少使用算法,一定时间段内使用次数(频率)最少的那个被移除;

    TTL(Time To Live )

    存活期,即从缓存中创建时间点开始直到它到期的一个时间段(不管在这个时间段内有没有访问都将过期)

     

    TTI(Time To Idle)

    空闲期,即一个数据多久没被访问将从缓存中移除的时间。

    Cache接口默认提供了如下实现:

    ConcurrentMapCache:使用java.util.concurrent.ConcurrentHashMap实现的Cache;

    GuavaCache:对Guava com.google.common.cache.Cache进行的Wrapper,需要Google Guava 12.0或更高版本,@since spring 4;

    EhCacheCache:使用Ehcache实现

    JCacheCache:对javax.cache.Cache进行的wrapper,@since spring 3.2;spring4将此类更新到JCache 0.11版本;


    三: Hello World

    1、在pom.xml中引入依赖

    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.2</version>
    </dependency>

    2、在src/main/resources/创建一个配置文件 ehcache.xml

    默认情况下Ehcache会自动加载classpath根目录下名为ehcache.xml文件,也可以将该文件放到其他地方在使用时指定文件的位置

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache>
        <!--表示硬盘上保存缓存的位置。默认是临时文件夹。-->
        <!--<diskStore path="java.io.tmpdir"/>-->
        <diskStore path="/logs/ehcache"/>
        <!--默认缓存配置,如果类没有做特定的设置,则使用这里配置的缓存属性。
           maxElementsInMemory  - 设置缓存中允许保存的最大对象(pojo)数量
           eternal -设置对象是否永久保存,如果为true,则缓存中的数据永远不销毁,一直保存。
           timeToIdleSeconds - 设置空闲销毁时间。只有eternal为false时才起作用。表示从现在到上次访问时间如果超过这个值,则缓存数据销毁
           timeToLiveSeconds-设置活动销毁时间。表示从现在到缓存创建时间如果超过这个值,则缓存自动销毁
           overflowToDisk - 设置是否在超过保存数量时,将超出的部分保存到硬盘上。-->
        <defaultCache
                maxElementsInMemory="1500"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="300"
                overflowToDisk="true"/>
     
        <cache name="demoCache"
               maxElementsInMemory="1000"
               eternal="true"
               timeToIdleSeconds="0"
               timeToLiveSeconds="0"
               overflowToDisk="true"/>

    <!-- helloworld缓存 -->
    <cache name="HelloWorldCache"
    maxElementsInMemory="1000"
    eternal="false"
    timeToIdleSeconds="5"
    timeToLiveSeconds="5"
    overflowToDisk="false"
    memoryStoreEvictionPolicy="LRU"/>

    <cache name="UserCache"
    maxElementsInMemory="1000"
    eternal="false"
    timeToIdleSeconds="1800"
    timeToLiveSeconds="1800"
    overflowToDisk="false"
    memoryStoreEvictionPolicy="LRU"/>
    </ehcache>

    3、测试类

    public class MyEhcache {
        public static void main(String[] args) {
            User user=new User("cache","123456","cache cache","","male",20); 
    
            // 获取缓存管理器
            CacheManager manager = CacheManager.create("src/main/resources/config/ehcache.xml");
           // 根据配置文件获得Cache实例
            Cache demo = manager.getCache("demoCache");
    
            // 清空Cache中的所有元素
            demo.removeAll();
            demo.put(new Element("hello","world"));
            demo.put(new Element(user.getUserName(),user)); 
    
    
            Element e=demo.get(user.getUserName()); 
    
            System.out.println(demo.get("hello").getObjectValue());
            System.out.println(((User)e.getObjectValue()).getUserRealName()); 
    
            //卸载缓存管理器
           // manager.shutdown();
        }
    }

    4、缓存配置

    一:xml配置方式:

    • diskStore : ehcache支持内存和磁盘两种存储

      • path :指定磁盘存储的位置
    • 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秒。

    二:编程方式配置

    Cache cache = manager.getCache("mycache"); 
    CacheConfiguration config = cache.getCacheConfiguration(); 
    config.setTimeToIdleSeconds(60); 
    config.setTimeToLiveSeconds(120); 
    config.setmaxEntriesLocalHeap(10000); 
    config.setmaxEntriesLocalDisk(1000000);

    5、Ehcache API

    • CacheManager:Cache的容器对象,并管理着(添加或删除)Cache的生命周期。
    // 可以自己创建一个Cache对象添加到CacheManager中
    public void addCache(Cache cache);
    public synchronized void removeCache(String cacheName);
    • Cache: 一个Cache可以包含多个Element,并被CacheManager管理。它实现了对缓存的逻辑行为

    • Element:需要缓存的元素,它维护着一个键值对, 元素也可以设置有效期,0代表无限制

    • 获取CacheManager的方式:

      可以通过create()或者newInstance()方法或重载方法来创建获取CacheManager的方式:

    public static CacheManager create();
    public static CacheManager create(String configurationFileName);
    public static CacheManager create(InputStream inputStream);
    public static CacheManager create(URL configurationFileURL);
    
    public static CacheManager newInstance();

    Ehcache的CacheManager构造函数或工厂方法被调用时,会默认加载classpath下名为ehcache.xml的配置文件。 
    如果加载失败,会加载Ehcache jar包中的ehcache-failsafe.xml文件,这个文件中含有简单的默认配置。

    // CacheManager.create() == CacheManager.create("./src/main/resources/ehcache.xml")
    // 使用Ehcache默认配置新建一个CacheManager实例
    CacheManager cacheManager = CacheManager.create();
    cacheManager = CacheManager.newInstance();
    
    cacheManager = CacheManager.newInstance("./src/main/resources/ehcache.xml");
    
    InputStream inputStream = new FileInputStream(new File("./src/main/resources/ehcache.xml"));
    cacheManager = CacheManager.newInstance(inputStream);
    
    String[] cacheNames = cacheManager.getCacheNames();  // [HelloWorldCache]

    四:Spring整合

    1、配置spring-ehcache.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:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
    
      <description>ehcache缓存配置管理文件</description>
    <!-- 启用缓存注解开关,这个是必须的,否则注解不会生效。另外,该注解一定要声明在spring主配置文件中才会生效 -->
    <!-- 自定义CacheKeyGenerator,当缓存没有定义key的时候有效-->
    <cache:annotation-driven cache-manager="cacheManager" key-generator="cacheKeyGenerator"/>
    <bean id="cacheKeyGenerator" class="com.esther.code.util.CacheKeyGenerator"/>
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 

    <property name="cacheManager" ref="ehcache"/> </bean>
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
    </bean>

    </beans>

     自定义缓存MyCacheable: 

    import org.springframework.cache.annotation.Cacheable;
    
    import java.lang.annotation.*;
    
    /**
     * @author  
     * 2018-04-23 18:38
     * $DESCRIPTION}
     */
    @Retention(RetentionPolicy.RUNTIME)//注解会在class中存在,运行时可通过反射获取
    @Target({ElementType.METHOD,ElementType.TYPE})//目标是方法
    @Documented//文档生成时,该注解将被包含在javadoc中,可去掉
    @Cacheable(value = "UserCache")
    public @interface MyCacheable {
    }

    CacheKeyGenerator :

    import com.google.common.hash.Hashing;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.stereotype.Component;
    import org.springframework.util.ClassUtils;
    
    import java.lang.reflect.Array;
    import java.lang.reflect.Method;
    import java.nio.charset.Charset;
    
    /**
     * @author 
     * 2018-04-23 16:01
     * $DESCRIPTION}
     */
    @Component("cacheKeyGenerator ")
    public class CacheKeyGenerator implements KeyGenerator {
        private Logger log= LoggerFactory.getLogger(getClass());
    
        // custom cache key
        public static final int NO_PARAM_KEY = 0;
        public static final int NULL_PARAM_KEY = 53;
    
        @Override
        public Object generate(Object target, Method method, Object... params) {
    
            StringBuilder key = new StringBuilder();
            key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append("(");
            if (params.length == 0) {
                return key.append(NO_PARAM_KEY).toString();
            }
            for (Object param : params) {
                if (param == null) {
                    log.warn("input null param for Spring cache, use default key={}", NULL_PARAM_KEY);
                    key.append(NULL_PARAM_KEY);
                } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
                    int length = Array.getLength(param);
                    for (int i = 0; i < length; i++) {
                        key.append(Array.get(param, i));
                        key.append('|');
                    }
                } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
                    key.append(param);
                } else {
                    log.warn("Using an object as a cache key may lead to unexpected results. " +
                            "Either use @Cacheable(key=..) or implement CacheKey. Method is " + target.getClass() + "#" + method.getName());
                    key.append(param.hashCode());
                }
                key.append(',');
            }
            // 去除最后一个逗号
            key.deleteCharAt(key.length()-1);
            key.append(")");
    
            String finalKey = key.toString();
            long cacheKeyHash = Hashing.murmur3_128().hashString(finalKey, Charset.defaultCharset()).asLong();
            log.debug("using cache key={}    hashCode={}", finalKey, cacheKeyHash);
            return key.toString();
        }
    }

    测试接口和实现类:

    public interface IEhcacheService {
    
        // 测试失效情况,有效期为5秒
        public String getTimestamp(String param);
    
        public String getDataFromDB(String key);
    
        public void removeDataAtDB(String key);
    
        public String refreshData(String key);
    
    
        public User findUserById(Integer userId);
    
        public boolean isReserved(Integer userId);
    
        public void removeUser(Integer userId);
    
        public void removeAllUser();
    
        // @Caching注解实现
        public String testCaching(String param);
    
        // 自定义注解实现
        User get(Integer userId);
    }
    import com.esther.code.annotation.MyCacheable;
    import com.esther.code.api.IEhcacheService;
    import com.esther.code.api.IUserService;
    import com.esther.code.model.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.cache.annotation.Caching;
    import org.springframework.stereotype.Service;
    
    /**
     * @author 
     * 2018-04-23 10:59
     * ehcache与spring注解实现
     */
    @Service("ehcacheService")
    public class EhcacheServiceImpl implements IEhcacheService {
    
        @Autowired
        private IUserService userService;
    
        // value的值和ehcache.xml中的配置保持一致
        @Cacheable(value = "HelloWorldCache", key = "#param")
        @Override
        public String getTimestamp(String param) {
            Long timestamp = System.currentTimeMillis();
            return timestamp.toString();
        }
    
        @Cacheable(value = "HelloWorldCache", key = "#key")
        @Override
        public String getDataFromDB(String key) {
            System.out.println("从数据库中获取数据...");
            return key + ":" + String.valueOf(Math.round(Math.random() * 1000000));
        }
    
        @CacheEvict(value = "HelloWorldCache", key = "#key")
        @Override
        public void removeDataAtDB(String key) {
            System.out.println("从数据库中删除数据");
        }
    
        // 使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
       // 每次都会执行方法,并将结果存入指定的缓存中
        @CachePut(value = "HelloWorldCache", key = "#key")
        @Override
        public String refreshData(String key) {
            System.out.println("模拟从数据库中加载数据");
            return key + "::" + String.valueOf(Math.round(Math.random()*1000000));
        }
    
        // ------------------------------------------------------------------------
    
        /**
         * 没有定义key的话,使用xml文件中配置的CacheKeyGenerator
         *
         * unless过滤方法返回值。当方法返回空值时,就不会被缓存起来
         * condition:对传入的参数进行筛选. 触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL。
         * expire:过期时间,单位为秒。
         * beforeInvocation: 是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存
         * @param userId
         * @return
         */
        @Override
        @Cacheable(value = "UserCache", condition = "#userId<=2", unless = "#result==null")
        public User findUserById(Integer userId) {
            System.out.println("模拟从数据库中查询数据");
            return userService.selectByPrimaryKey(userId);
        }
    
        /**
         * condition:对传入的参数进行筛选. 触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL。
         * expire:过期时间,单位为秒。
         * @param userId
         * @return
         */
        @Override
        @Cacheable(value = "UserCache", condition = "#userId<=2")
        public boolean isReserved(Integer userId) {
            System.out.println("UserCache:" + userId);
            return false;
        }
    
        //清除掉UserCache中某个指定key的缓存
        @Override
        @CacheEvict(value = "UserCache", key = "'user:' + #userId")
        public void removeUser(Integer userId) {
            System.out.println("UserCache remove:" + userId);
        }
    
        //清除掉UserCache中全部的缓存
        @Override
        @CacheEvict(value = "UserCache", allEntries = true)
        public void removeAllUser() {
            System.out.println("UserCache delete all");
        }
    
        /**
         * 多个缓存组合的@Caching
         * @param param
         * @return
         */
        @Override
        @Caching(evict = @CacheEvict(value = "UserCache",allEntries=true),cacheable = {@Cacheable("HelloWorldCache")})
        public String testCaching(String param){
            System.out.println("UserCache delete all");
            Long timestamp = System.currentTimeMillis();
            return timestamp.toString();
        }
    
        /**
         * 自定义缓存MyCacheable
         * @param userId
         * @return
         */
        @Override
        @MyCacheable
        public User get(Integer userId) {
            return userService.selectByPrimaryKey(userId);
        }
    }

     五、Dummy CacheManager 的配置和作用

      有的时候,我们在代码迁移、调试或者部署的时候,恰好没有 cache 容器,比如 memcache 还不具备条件,h2db 还没有装好等,如果这个时候你想调试代码,岂不是要疯掉?这里有一个办法,在不具备缓存条件的时候,在不改代码的情况下,禁用缓存。

    方法就是修改 spring*.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:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
    
        <description>ehcache缓存配置管理文件</description>
    
        <!-- 启用缓存注解开关,这个是必须的,否则注解不会生效。另外,该注解一定要声明在spring主配置文件中才会生效 -->
        <!-- 自定义CacheKeyGenerator,当缓存没有定义key的时候有效-->
    <!--mode属性,可选值有proxy和aspectj。默认是使用proxy。
    当mode为proxy时,只有缓存方法在外部被调用的时候Spring Cache才会发生作用,
    这也就意味着如果一个缓存方法在其声明对象内部被调用时Spring Cache是不会发生作用的。而mode为aspectj时就不会有这种问题。
    另外使用proxy时,只有public方法上的@Cacheable等标注才会起作用,如果需要非public方法上的方法也可以使用Spring Cache时把mode设置为aspectj。

    此外,<cache:annotation-driven/>还可以指定一个proxy-target-class属性,表示是否要代理class,默认为false。
    我们前面提到的@Cacheable、@cacheEvict等也可以标注在接口上,这对于基于接口的代理来说是没有什么问题的,
    但是需要注意的是当我们设置proxy-target-class为true或者mode为aspectj时,是直接基于class进行操作的,
    定义在接口上的@Cacheable等Cache注解不会被识别到,那对应的Spring Cache也不会起作用了。-->
        <cache:annotation-driven cache-manager="cacheManager" key-generator="cacheKeyGenerator"/>
        <bean id="cacheKeyGenerator" class="com.esther.code.util.CacheKeyGenerator"/>
    
        <!--一般的缓存管理器,如EhCache-->
        <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
            <property name="cacheManager" ref="ehcache"/>
        </bean>
    
        <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
            <property name="configLocation" value="classpath:ehcache.xml"/>
        </bean>
    
        <!--Dummy CacheManager:在找不到对应缓存时(如UserCache),可以设置标志位fallbackToNoOpCache=true,禁用缓存。
        如果找不到对应缓存,且fallbackToNoOpCache=false,抛异常java.lang.IllegalArgumentException: Cannot find cache named 'UserCache' for CacheEvictOperation-->
        <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
            <property name="cacheManagers">
                <list>
                    <ref bean="ehcacheManager"/>
                </list>
            </property>
            <property name="fallbackToNoOpCache" value="true"/>
        </bean>
    </beans>
  • 相关阅读:
    Pandas数据分析 (三)
    Pandas数据分析 (二)
    Pandas数据分析 (一)
    Django后台应用管理名称修改
    Jupyter Notebooks 配置
    Hadoop完全分布式搭建流程
    Java学习笔记(五)
    微信小程序学习笔记(一)
    redis windows版安装
    Linux计划任务
  • 原文地址:https://www.cnblogs.com/esther-qing/p/8874529.html
Copyright © 2011-2022 走看看