SpringBoot系统搭建集成-014-如何使用ehcache缓存

Lison <cundream@163.com>, v1.0.0, 2019.10.05

SpringBoot系统搭建集成-014-如何使用ehcache缓存

Spring Boot的cache支持多种缓存,参考缓存支持,其中常用的有EhCache和Redis,Redis需要安装redis服务器,而EhCache不依赖任何第三方软件,只需引入jar即可。下面主要介绍ehcache的集成方法。

添加依赖

在pom.xml里添加ehcache相关的依赖

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

创建ehcache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
 <defaultCache
            maxElementsInMemory="20000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

    <!--
    缓存文件名:user,同样的可以配置多个缓存
    maxElementsInMemory:内存中最多存储
    eternal:外部存储
    overflowToDisk:超出缓存到磁盘
    diskPersistent:磁盘持久化
    timeToLiveSeconds:缓存时间
    diskExpiryThreadIntervalSeconds:磁盘过期时间
    -->
    <cache name="users"
           maxElementsInMemory="20000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="false"
           timeToLiveSeconds="0"
           diskExpiryThreadIntervalSeconds="120"/>

</ehcache>

cache的属性说明:

  • name:缓存的名称。
  • maxElementsInMemory:缓存中最大元素个数。0表示不限制
  • eternal:对象是否永久有效,一但设置了,timeout将不起作用,元素永久存在。
  • clearOnFlush:内存数量最大时是否清除。
  • timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  • timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  • diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  • diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。
  • maxElementsOnDisk:硬盘最大缓存个数。
  • overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  • diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache
  • 都应该有自己的一个缓冲区。
  • maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  • memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。

配置ehcache配置

spring:
  cache:
    ehcache:
      config: ehcache.xml

开启缓存支持

在启动类上添加注解**@EnableCaching**以开启缓存支持。

@EnableCaching
@MapperScan("com.github.cundream.springbootbuilding.mapper")
@SpringBootApplication
public class SpringbootbuildingApplication  extends SpringBootServletInitializer {


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootbuildingApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringbootbuildingApplication.class, args);
    }

}

代码中使用缓存

Spring提供了4个声明式缓存注解:

注解解释
@Cacheable在方法执行前Spring先查看缓存中是否存在,如果存在,则直接返回缓存数据,若不存在则调用方法并将方法返回值放进缓存
@CachePut无论怎样,都会将方法的返回值放到缓存中。@CachePut的属性与@Cacheable保持一致
@CacheEvict将一条或多条数据从缓存中删除。
@Caching可以通过@Caching注解组合多个注解策略在一个方法上


​ 1、添加缓存

添加缓存只需要在方法上面添加缓存注解即可,我们对com.github.cundream.springbootbuilding.service.impl.UserServiceImpl#getUserList`方法做如下修改:

 /**
     *
     * @param userId
     * @return
     */
    @Cacheable(cacheNames = "users", key = "#userId")
    @Override
    public User getUserListInfo(Long userId) {
        return  userMapper.getUserInfoById(userId);

    }

2、删除缓存
当我们删除用户、修改用户等操作时,需要把缓存也更新。下面例子使用@CacheEvict注解来删除缓存

@CacheEvict(value = "users",key = "#id")
public void evictUser(Long id) {
    System.out.println("evict user:" + id);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值