Spring Boot 簡單使用EhCache緩存框架的方法
我的環(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)文章
Ribbon負(fù)載均衡服務(wù)調(diào)用的示例詳解
Rbbo其實(shí)就是一個軟負(fù)載均衡的客戶端組件,他可以和其他所需請求的客戶端結(jié)合使用,這篇文章主要介紹了Ribbon負(fù)載均衡服務(wù)調(diào)用案例代碼,需要的朋友可以參考下2023-01-01Spring?Security短信驗(yàn)證碼實(shí)現(xiàn)詳解
本文主要介紹了Spring?Security短信驗(yàn)證碼的實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-11-11解析web.xml中在Servlet中獲取context-param和init-param內(nèi)的參數(shù)
本篇文章是對web.xml中在Servlet中獲取context-param和init-param內(nèi)的參數(shù)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07Java編程實(shí)現(xiàn)的模擬行星運(yùn)動示例
這篇文章主要介紹了Java編程實(shí)現(xiàn)的模擬行星運(yùn)動,涉及java基于swing組建繪制動態(tài)效果及數(shù)值運(yùn)算相關(guān)操作技巧,并總結(jié)分析了java面向?qū)ο蟮南嚓P(guān)特性,需要的朋友可以參考下2018-04-04spring-boot.version2.6升級到2.7.18后security報(bào)錯問題
這篇文章主要介紹了spring-boot.version2.6升級到2.7.18后security報(bào)錯問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08servlet之session工作原理簡介_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了servlet之session工作原理簡介,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07springboot整合JavaCV實(shí)現(xiàn)視頻截取第N幀并保存圖片
這篇文章主要為大家詳細(xì)介紹了springboot如何整合JavaCV實(shí)現(xiàn)視頻截取第N幀并保存為圖片,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-08-08Java中位運(yùn)算(移位、位與、或、異或、非) 的簡單實(shí)例
Java中位運(yùn)算(移位、位與、或、異或、非) 的簡單實(shí)例,需要的朋友可以參考一下2013-02-02