Spring Boot中集成EnCache

介绍:

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。

使用:

1、导入依赖:

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

2、在application.properties中添加配置

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

3、ehcache.xml文中的内容(因为无法连接到http://ehcache.org/ehcache.xsd,所有在访问了该网站后copy了一份ehcache.xsd到本地了)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <!--
    eternal:设置缓存中对象是否为永久的
    timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false
                      对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
    timeToLiveSeconds:缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,
                     这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
    overflowToDisk:内存不足时,是否启用磁盘缓存。
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
     -->
     <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" />

    <cache
        name="student"
        maxEntriesLocalHeap="2000"
        eternal="false"
        timeToIdleSeconds="3600"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        statistics="true">
    </cache>
</ehcache>

4、server层,

     @CacheConfig :可以抽取公共的配置

     @Cacheable:表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不在调用该方法。

     @CachePut: 不仅缓存结果,而且执行代码端

     @CacheEvict: 删除无效的缓存数据,allEntries:true时,移除所有的数据

                                                                 beforeInvocation:非必须,默认false:在调用方法之后移除数据。true相反

    公有参数:value :缓存的位置名称,表面将值缓存到哪个cache,这个在encache.xml文件中配置

               key:相当于key-value中的key,但是这个key是系统用来访问调用的。最好要唯一

               condition:触发条件,只有满足条件才会加入缓存。

               keyGenerator:用于指定key生成器,非必须。若指定,则需实现org.springframework.cache.interceptor.KeyGenerator接口

               cacheManager :指定使用哪个缓存管理器,非必须。当有多个时必须使用。

               cacheResolver:用于指定使用哪个缓存解析器,非必须。需要通过org.springframework.cache.interceptor.CacheResolver接口来                                           实现自己的缓存解析器

package com.example.demo.server;

import com.example.demo.bean.Student;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;


/*相当于抽取公共配置*/
@CacheConfig(cacheNames = "student")
public interface StudentServer {

    @Cacheable(key = "'student:'+#id")
    public Student findStudentById(int id);

}
原文地址:https://www.cnblogs.com/minblog/p/12517029.html