Spring Boot 簡單使用EhCache緩存框架的方法
更新時間:2018年07月20日 14:11:03 作者:ImWiki
本篇文章主要介紹了Spring Boot 簡單使用EhCache緩存框架的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
我的環(huán)境是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>
使用
需要持久化的類需要實現(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
}
}
// 獲取緩存實例
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"/>就可以寫入文件,重啟服務數(shù)據也不會丟失。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Spring Boot中的那些條件判斷的實現(xiàn)方法
這篇文章主要介紹了Spring Boot中的那些條件判斷的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04
Mybatis實戰(zhàn)之TypeHandler高級進階
本文主要介紹了自定義的枚舉TypeHandler的相關知識,具有很好的參考價值,下面跟著小編一起來看下吧2017-02-02

