温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

EhCache缓存框架怎么在Spring Boot中使用

发布时间:2021-03-26 17:06:39 来源:亿速云 阅读:151 作者:Leah 栏目:编程语言

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

EhCache缓存框架怎么在Spring Boot中使用

看完上述内容,你们掌握EhCache缓存框架怎么在Spring Boot中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI