Spring Boot 简单使用EhCache缓存框架的方法

时间:2022-09-22 20:18:34

我的环境是gradle + kotlin + spring boot,这里介绍ehcache缓存框架在spring boot上的简单应用。

在build.gradle文件添加依赖

?
1
2
compile("org.springframework.boot:spring-boot-starter-cache")
compile("net.sf.ehcache:ehcache")

修改application的配置,增加@enablecaching配置

?
1
2
3
4
5
6
7
8
9
10
11
@mapperscan("com.xxx.xxx.dao")
@springbootapplication(scanbasepackages= arrayof("com.xxx.xxx"))
// 启用缓存注解
@enablecaching
// 启动定时器
@enablescheduling
open class myapplication {}
 
fun main(args: array<string>) {
  springapplication.run(myapplication::class.java, *args)
}

resources添加文件ehcache.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<ehcache xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
     xsi:nonamespaceschemalocation="ehcache.xsd">
  <diskstore path="mycache.ehcache"/>
 
  <defaultcache
      maxelementsinmemory="100"
      eternal="true"
      overflowtodisk="true"/>
 
  <cache
      name="usercache"
      maxelementsinmemory="10"
      eternal="false"
      timetoidleseconds="0"
      timetoliveseconds="0"
      overflowtodisk="true"
      maxelementsondisk="20"
      diskpersistent="true"
      diskexpirythreadintervalseconds="120"
      memorystoreevictionpolicy="lru"/>
</ehcache>

使用

需要持久化的类需要实现serializable序列化接口,不然无法写入硬盘

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class user : serializable {
  var id: int = 0
  var name: string? = null
 
  constructor()
  
  constructor(id: int, name: string?) {
    this.id = id
    this.name = name
  }
}
// 获取缓存实例
val usercache = cachemanager.getinstance().getcache("usercache")
// 写入缓存
val element = element("1000", user(1000,"wiki"))
usercache.put(element)
// 读取缓存
val user = usercache.get("1000").objectvalue as user

写入硬盘

只要增加<diskstore path="mycache.ehcache"/>就可以写入文件,重启服务数据也不会丢失。

Spring Boot 简单使用EhCache缓存框架的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/3e35009ad3b