我的環(huán)境是gradle + kotlin + spring boot,這里介紹ehcache緩存框架在spring boot上的簡單應(yīng)用。
在build.gradle文件添加依賴
1
2
|
compile( "org.springframework.boot:spring-boot-starter-cache" ) compile( "net.sf.ehcache:ehcache" ) |
修改application的配置,增加@enablecaching
配置
1
2
3
4
5
6
7
8
9
10
11
|
@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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<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序列化接口,不然無法寫入硬盤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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ì)丟失。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/3e35009ad3b