欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 簡單使用EhCache緩存框架的方法

 更新時間:2018年07月20日 14:11:03   作者:ImWiki  
本篇文章主要介紹了Spring Boot 簡單使用EhCache緩存框架的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

我的環(huán)境是Gradle + Kotlin + Spring Boot,這里介紹EhCache緩存框架在Spring Boot上的簡單應(yīng)用。

在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>

使用

需要持久化的類需要實(shí)現(xiàn)Serializable序列化接口,不然無法寫入硬盤

class User : Serializable {
  var id: Int = 0
  var name: String? = null

  constructor()
  
  constructor(id: Int, name: String?) {
    this.id = id
    this.name = name
  }
}
// 獲取緩存實(shí)例
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"/>就可以寫入文件,重啟服務(wù)數(shù)據(jù)也不會丟失。


以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論