Spring Boot 简单使用EhCache缓存框架的方法

网友投稿 338 2023-01-25


Spring Boot 简单使用EhCache缓存框架的方法

我的环境是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) {

SpringApplication.run(MyApplication::class.java, *args)

}

在resources添加文件ehcache.xml

xsi:noNamespaceSchemaLocation="ehcache.xsd">

maxElementsInMemory="100"

eternal="true"

overflowToDisk="true"/>

name="userCache"

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="0"

timeToLiveSeconds="0"

overflowToDisk="true"

maxElementsOnDisk="20"

diskPersistent="true"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU"/>

xsi:noNamespaceSchemaLocation="ehcache.xsd">

maxElementsInMemory="100"

eternal="true"

overflowToDisk="true"/>

name="userCache"

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="0"

timeToLiveSeconds="0"

overflowToDisk="true"

maxElementsOnDisk="20"

diskPersistent="true"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU"/>

maxElementsInMemory="100"

eternal="true"

overflowToDisk="true"/>

name="userCache"

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="0"

timeToLiveSeconds="0"

overflowToDisk="true"

maxElementsOnDisk="20"

diskPersistent="true"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU"/>

name="userCache"

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="0"

timeToLiveSeconds="0"

overflowToDisk="true"

maxElementsOnDisk="20"

diskPersistent="true"

diskExpiryThreadIntervalSeconds="120"

memoryStoreEvictionPolicy="LRU"/>

使用

需要持久化的类需要实现Serializable序列化接口,不然无法写uLyGTzt入硬盘

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

写入硬盘

只要增加就可以写入文件,重启服务数据也不会丢失。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何开展接口自动化测试(如何开展接口自动化测试工作)
下一篇:Java正则表达式,提取双引号中间的部分方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~