Spring Boot 簡(jiǎn)單使用EhCache緩存框架的方法
我的環(huán)境是Gradle + Kotlin + Spring Boot,這里介紹EhCache緩存框架在Spring Boot上的簡(jiǎn)單應(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
// 啟動(dòng)定時(shí)器
@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序列化接口,不然無(wú)法寫入硬盤
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ù)也不會(huì)丟失。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot中的那些條件判斷的實(shí)現(xiàn)方法
這篇文章主要介紹了Spring Boot中的那些條件判斷的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Mybatis實(shí)戰(zhàn)之TypeHandler高級(jí)進(jìn)階
本文主要介紹了自定義的枚舉TypeHandler的相關(guān)知識(shí),具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧2017-02-02
java中獲取當(dāng)前服務(wù)器的Ip地址的方法
本篇文章主要介紹了java中獲取當(dāng)前服務(wù)器的Ip地址的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02
Dubbo+zookeeper搭配分布式服務(wù)的過(guò)程詳解
Dubbo作為分布式架構(gòu)比較后的框架,同時(shí)也是比較容易入手的框架,適合作為分布式的入手框架,下面是簡(jiǎn)單的搭建過(guò)程,對(duì)Dubbo+zookeeper分布式服務(wù)搭建過(guò)程感興趣的朋友一起看看吧2022-04-04
Spring注解配置實(shí)現(xiàn)過(guò)程詳解
這篇文章主要介紹了Spring注解配置實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

