1.什么是EhCache

EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来,是进程中的缓存系统
它提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案,快速简单。

2.注解使用

2.1 @Cacheable

应用到读取数据的方法,即可缓存的方法,如查找方法
先从缓存中读取,如果没有再用相应方法获取数据,然后把数据添加到缓存中。
该注解主要有下面几个参数:

  • value:cacheNames: 两个等同的参数(cacheNames为Spring 4新增,作为value的别名) ,用于指定缓存存储的集合名。
    由于Spring 4中新增了@CacheConfig,因此在Spring 3中原本必须有的value属性,也成为非必需项了
  • key: 缓存对象存储在Map集合中的key值,非必需,
    缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如: @Cacheable(key = "#p0"),使用函数第一个参数作为缓存的key值
  • condition: 缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存
    比如: @Cacheable(key = "#p0", condition = "#p0.length()< 3"),表示只有当第一个参数的长度小于3的时候才会被缓存。
  • unless:另外一个缓存条件参数,非必需,需使用SpEL表达式。
    它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断。
  • keyGenerator: 用于指定key生成体,非必需。
    若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.Interceptor.KeyGenerator接口,并使用该参数来指定。
    需要注意的是:该参数与key是互斥的
  • cacheManager: 用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用
  • cacheResolver: 用于指定使用那个缓存解析器,非必需。需通过org,springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器,并用该参数指定。

2.2 @CachePut

应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存,@CachePut的参数与@Cacheable类似

2.3 @CacheEvict

应用到移除数据的方法上,如删除方法,调用方法时会从缓存中移除相应的数据
参数:

  • allEintries: 非必需,默认为false.当为true时, 会移除所有数据
  • beforeInvocation: 非必需,默认为false, 会在调用方法之后移除数据。当为true时,会在调用方法之前移除数据。

3.pom.xml

<!--    EhCache-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>

4.ehcache.xml

<ehcache name="mycache">
    <diskStore path="C:SpringBoot\cache"></diskStore>
<!--name :缓存名称。-->
<!--eternal="false":缓存最大数目-->
<!--maxElementsOnDisk:硬盘最大缓存个数-->
<!--eternal:对象是否永久有效,一但设置了,timeout将不起作用。-->
<!--overflowToDisk:是否保存到磁盘,当系统宕机时-->
<!--timeToIdleSeconds :设置对象在失效前的允许闲置时间(单位:秒)。-->
<!--    仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。-->
<!--timeToLiveSeconds :设置对象在失效前允许存活时间(单位:秒)。-->
<!--    最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。-->
<!--diskPersistent:是否缓存虚拟机重启期数据whether the disk store persists between-->
<!--    restarts of the Virtual Machine. The default value is false.-->
<!--diskSpoolBufferSizeMB:这个参数设置Diskstore (磁盘缓存)的缓存区大小。默认是30MB。每个Cache 都应该有自己的一个缓冲区。-->
<!--diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。-->
<!--memoryStoreEvictionPolicy:当达到maxE1ementsInMemory限制时,Ehcache将根据指定的策略去清理内存。-->
<!--    默认策略是LRU (最近最少使用)。你可以设置为FIFO (先进先出),LFU (较少使用) -->
<!--clearOnFlush:内存数量最大时是否清除。-->
<!--memoryStoreEvictionPolicy:可选策略有: LRU (最近最少使用,默认策略)、FIFO (先进先出)、 LFU (最少访问次数)。-->
   <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        maxElementsOnDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
   </defaultCache>

    <cache
        name="users"
        eternal="false"
        maxElementsInMemory="100"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="0"
        timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU">
    </cache>

</ehcache>

5.application.yml

spring:
    cache:
    ehcache:
      config: classpath:ehcache.xml

6.启动类

@EnableCaching
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class);

    }
}

7.实体类

public class User implements Serializable {
    @ApiModelProperty(value = "用户id")
    private int id;
    @ApiModelProperty(value = "用户名")
    private String name;
    @ApiModelProperty(value = "用户密码")
    private String password;

8.service层

@Cacheable(value = "users", key = "#id")
    public User queryUserById(int id){
        return userDao.queryUserById(id);
    }
  //多参数
  //@Cacheable(value = "users", key = "#javabean.prop1+'-'+#javabean.prop2")