java进程内缓存框架ehcache

ehcache是java进程内缓存框架!快速精干!适用于单个应用程序或者对缓存访问速度要求很高的应用!如果是分布式、缓存共享、大型系统以及缓存数据内容很大时,推荐使用redis!
ehcache同spring项目整合方案
1、引入依赖jar
    <dependency> 
        <groupId>net.sf.ehcache</groupId> 
        <artifactId>ehcache</artifactId>
        <version>2.10.2</version> 
    </dependency>
2、引入配置文件(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="java.io.tmpdir/ehcache"/>
     <!-- 默认缓存 --> 
    <defaultCache 
        maxEntriesLocalHeap="10000" 
        eternal="false" 
        timeToIdleSeconds="120" 
        timeToLiveSeconds="120" 
        maxEntriesLocalDisk="10000000"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="LRU"> 
        <persistence strategy="localTempSwap"/>
    </defaultCache> 
    <!-- helloworld缓存 --> 
    <cache name="HelloWorldCache" 
    maxElementsInMemory="1000"
    eternal="false" 
    timeToIdleSeconds="5" 
    timeToLiveSeconds="5" 
    overflowToDisk="false" 
    memoryStoreEvictionPolicy="LRU"/> 
    </ehcache>
配置说明:
    diskStore : ehcache支持内存和磁盘两种存储
    defaultCache : 默认的缓存
    cache :自定的缓存
    name : 缓存的名称
    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秒。
二、同spring项目整合
    1、引入依赖
    2、引入ehcache.xml配置文件
    3、引入与spring整合配置文件
    <?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> 
    <!-- 启用缓存注解开关 --> 
    <cache:annotation-driven cache-manager="cacheManager"/> 
    <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>
    4、创建工具类
    public interface EhcacheService { // 测试失效情况,有效期为5秒 
    public String getTimestamp(String param); 
    public String getDataFromDB(String key); 
    public void removeDataAtDB(String key); 
    public String refreshData(String key); 
    public User findById(String userId); 
    public boolean isReserved(String userId); 
    public void removeUser(String userId); 
    public void removeAllUser(); }

    @Service 
    public class EhcacheServiceImpl implements EhcacheService{ 
    // 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(value="HelloWorldCache", key="#key") 
    @Override 
    public String refreshData(String key) { 
    System.out.println("模拟从数据库中加载数据"); 
    return key + "::" + 
    String.valueOf(Math.round(Math.random()*1000000)); 
    } 
    // ------------------------------------------------------------------------ 
    @Cacheable(value="UserCache", key="'user:' + #userId") 
    public User findById(String userId) { 
        System.out.println("模拟从数据库中查询数据"); 
        return (User) new User("1", "mengdee"); 
    } 

    @Cacheable(value="UserCache", condition="#userId.length()<12") 
    public boolean isReserved(String userId) { 
        System.out.println("UserCache:"+userId); return false; 
    } 
    //清除掉UserCache中某个指定key的缓存 
    @CacheEvict(value="UserCache",key="'user:' + #userId") 
    public void removeUser(String userId) { 
        System.out.println("UserCache remove:"+ userId); 
    } 
    //清除掉UserCache中全部的缓存 
    @CacheEvict(value="UserCache", allEntries=true) 
    public void removeAllUser() { 
        System.out.println("UserCache delete all"); }
    }
6、缓存注解使用介绍
    @Cacheable
        表示方法可以缓存,第一次方法时缓存数据,在有限的时间内,不在执行方法中的代码,直接使用缓存中的内容!
        Value:缓存位置名称
        Key:缓存的key,如果要引用参数值使用井号加参数名,如:#userId,
        Condition:触发条件
    @CachePut
        不仅会缓存方法的结果,还会执行方法的代码段!它支持的属性和用法都与@Cacheable一致。
    @CacheEvict
        所修饰的方法是用来删除失效或无用的缓存数据。
        value:缓存位置名称
        key:缓存的key
        condition:触发条件
        allEntries:true表示清除value中的全部缓存,默认为false

猜你喜欢

转载自blog.csdn.net/weixin_42863291/article/details/81709935