前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot配置EhCache缓存

SpringBoot配置EhCache缓存

作者头像
崔笑颜
发布2020-06-08 16:18:23
1.3K0
发布2020-06-08 16:18:23
举报
文章被收录于专栏:小小码农一个。

添加依赖

代码语言:javascript
复制
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

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

添加配置

在 src/main/resources 目录下创建 ehcache.xml 文件,内容如下:

代码语言:javascript
复制
<?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>

    <!-- 自定义缓存 -->
    <cache name="department"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="50"
           timeToLiveSeconds="50"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>

说明

代码语言:javascript
复制
name:Cache 的唯一标识
maxElementsInMemory:内存中允许存储的最大的元素个数
maxElementsOnDisk:硬盘最大缓存个数,0代表无限个
clearOnFlush:内存数量最大时是否清除
eternal:缓存对象是否永久有效,如果是,超时设置将被忽略
overflowToDisk:内存不足(超过 maxElementsInMemory)时,是否启用磁盘缓存
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds:缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间
diskPersistent:是否将缓存数据持久化到磁盘上,如果为 true,JVM 重启数据依然存在。默认值是false
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
memoryStoreEvictionPolicy:当达到 maxElementsInMemory 限制时,Ehcache 将根据指定策略清除内存。默认为 LRU(最近最少使用),其他策略有 FIFO(先进先出),LFU(较少使用)

application.properties :

代码语言:javascript
复制
# 缓存类型(ehcache、redis)
spring.cache.type=ehcache

# ehcache 配置文件
spring.cache.ehcache.config=classpath:ehcache.xml

# 打印日志,查看 sql
logging.level.com.light.springboot=DEBUG

编码

在持久层篇的基础上,结合 Mybatis 测试:

Service 层:

代码语言:javascript
复制
@CacheConfig(cacheNames = "department")
@Service
public class DepartmentService {

  @Autowired
  private DepartmentMapper departmentMapper;

  @CachePut(key = "#department.id")
  public Department save(Department department) {
    System.out.println("保存 id=" + department.getId() + " 的数据");
    this.departmentMapper.insert(department);
    return department;
  }

  @CachePut(key = "#department.id")
  public Department update(Department department) {
    System.out.println("修改 id=" + department.getId() + " 的数据");
    this.departmentMapper.update(department);
    return department;
  }

  @Cacheable(key = "#id")
  public Department getDepartmentById(Integer id) {
    System.out.println("获取 id=" + id + " 的数据");
    Department department = this.departmentMapper.getById(id);
    return department;
  }

  @CacheEvict(key = "#id")
  public void delete(Integer id) {
    System.out.println("删除 id=" + id + " 的数据");
    this.departmentMapper.deleteById(id);
  }
}

控制层:

代码语言:javascript
复制
@Controller
@RequestMapping("department")
@ResponseBody
public class DepartmentController {

  @Autowired
  private DepartmentService departmentService;

  @RequestMapping("save")
  public Map<String,Object> save(Department department) {
    this.departmentService.save(department);

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("code", "200");
    map.put("msg", "保存成功");
    return map;
  }

  @RequestMapping("get/{id}")
  public Map<String,Object> get(@PathVariable("id") Integer id) {
    Department department = this.departmentService.getDepartmentById(id);

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("code", "200");
    map.put("msg", "获取成功");
    map.put("data", department);
    return map;
  }

  @RequestMapping("update")
  public Map<String,Object> update(Department department) {
    this.departmentService.update(department);

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("code", "200");
    map.put("msg", "修改成功");
    return map;
  }

  @RequestMapping("delete/{id}")
  public Map<String,Object> delete(@PathVariable("id") Integer id) {
    this.departmentService.delete(id);

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("code", "200");
    map.put("msg", "删除成功");
    return map;
  }
}

启动类:

添加 @EnableCaching 注解,开启缓存功能。

测试说明

由于 ehcache 缓存是存储在应用的内存中,如果使用 junit 测试,方法执行完毕缓存就释放了,无法正常测试缓存效果,因此测试使用发起 http 请求的形式。

发起保存请求:

发起保存请求:

代码语言:javascript
复制
保存 id=2 的数据
2017-12-06 14:50:48.800 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert        : ==>  Preparing: insert into department(id,name,descr) values(?,?,?)
2017-12-06 14:50:48.801 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert        : ==> Parameters: 2(Integer), Ehcache 部门(String), Ehcache(String)
2017-12-06 14:50:48.868 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert        : <==    Updates: 1

保存成功后,立刻发起查询请求,没有日志打印,但返回对象数据,说明数据是从缓存中获取。

发起修改请求:

代码语言:javascript
复制
修改 id=2 的数据
2017-12-06 14:51:16.588 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update        : ==>  Preparing: update department set name = ? , descr = ? where id = ?
2017-12-06 14:51:16.589 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update        : ==> Parameters: Ehcache 部门2(String), Ehcache2(String), 2(Integer)
2017-12-06 14:51:16.657 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update        : <==    Updates: 1

修改成功后,立刻发起查询请求,没有日志打印,但返回修改后的对象数据,说明缓存中的数据已经同步。

发起删除请求:

代码语言:javascript
复制
删除 id=2 的数据
2017-12-06 14:52:07.572 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById    : ==>  Preparing: delete from department where id = ?
2017-12-06 14:52:07.572 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById    : ==> Parameters: 2(Integer)
2017-12-06 14:52:07.613 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById    : <==    Updates: 1

删除成功后,立刻发起查询请求,控制台打印 sql 语句,说明缓存数据被删除,需要查询数据库。

代码语言:javascript
复制
获取 id=2 的数据
2017-12-06 14:52:40.324 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById       : ==>  Preparing: select id,name,descr from department where id = ?
2017-12-06 14:52:40.325 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById       : ==> Parameters: 2(Integer)
2017-12-06 14:52:40.328 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById       : <==      Total: 0
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-09-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 添加依赖
  • 添加配置
  • 说明
  • application.properties :
  • 编码
  • 控制层:
  • 测试说明
    • 发起保存请求:
      • 发起修改请求:
        • 发起删除请求:
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档