ITPub博客

首页 > IT职业 > IT职场 > Spring Boot:简单使用EhCache缓存框架

Spring Boot:简单使用EhCache缓存框架

IT职场 作者:firefule 时间:2021-09-09 09:38:04 0 删除 编辑

我的环境是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// 启动定时器@EnableSchedulingopen class MyApplication {}fun main(args: Array) {
    SpringApplication.run(MyApplication::class.java, *args)
}

在resources添加文件ehcache.xml


    

    

    
使用

需要持久化的类需要实现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
写入硬盘

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

图片描述

image.png



作者:ImWiki
链接:https://www.jianshu.com/p/3e35009ad3b9

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1834/viewspace-2805427/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: php检测邮箱密码
请登录后发表评论 登录
全部评论

注册时间:2019-07-24

  • 博文量
    105
  • 访问量
    15349