在Spring Boot中对于缓存的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存。只需要在工程中加入ehcache.xml配置文件并在pom.xml中增加ehcache依赖,框架只要发现该文件,就会创建EhCache的缓存管理器。

引入依赖

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

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

配置

  • 添加ehcache配置文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <cache name="lemonCache"
           eternal="false"
           maxEntriesLocalHeap="0"
           timeToIdleSeconds="200"/>

    <!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
    <!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->
    <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,
    如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。
    只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态 -->
</ehcache>
  • 直接使用默认配置并在application.yml中配置ehcache.xml路径
spring:
  cache:
    ehcache:
      config: ehcache.xml
  • 也可使用自定义config配置类
@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * ehcache管理器
     * @param bean
     * @return
     */
    @Bean(name = "appEhCacheCacheManager")
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean) {
        return new EhCacheCacheManager(bean.getObject());
    }

    /**
     * 据shared与否的设置,Spring分别通过CacheManager.create()或new CacheManager()方式来创建一个ehcache基地
     *
     * @return
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }
}

在Spring Boot主类中增加@EnableCaching注解开启缓存功能,如过单独配置了config类,可直接在config配置类上加上此注解,而此处无需再加

@SpringBootApplication
@EnableScheduling
@EnableCaching
public class HestiaApplication extends SpringBootServletInitializer{

	public static void main(String[] args) {
		SpringApplication.run(HestiaApplication.class, args);
	}
	
}

使用ehcache

使用ehcache主要通过spring的缓存机制,上面我们将spring的缓存机制使用了ehcache进行实现,所以使用方面就完全使用spring缓存机制就行了。主要注解如下:

@Cacheable:将方法的返回值加入到缓存中
@CacheEvict:清除缓存

参数解释:

value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name

key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL

condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL

allEntries:CacheEvict参数,true表示清除value中的全部缓存,默认为false