溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2021-03-26 17:06:39 來源:億速云 閱讀:198 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女