当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot 简单使用EhCache缓存框架的方法

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

在build.gradle文件添加依赖

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

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

@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

<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序列化接口,不然无法写入硬盘

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"/>就可以写入文件,重启服务数据也不会丢失。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网