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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

ImWiki   2021-03-31 我要评论

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


猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们