美文网首页spring-boot 踩坑程序员
spring-boot-cache应用小结(Redis篇)

spring-boot-cache应用小结(Redis篇)

作者: aef5bc56a01e | 来源:发表于2019-03-14 16:36 被阅读1次

    背景

    最近公司项目处于停滞期,私想着是时候优化代码了,于是想到了缓存的应用。于是遇到了一系列的问题,在此稍作总结。
    之前自己用redis存东西的时候,都是手动操作,略显麻烦,于是就想着用一下spring-cache。

    spring-boot-cache

    spring cache支持天然支持多种缓存

    • GENERIC
    • JCache
    • EhCache
    • HAZELCAST
    • INFINISPAN
    • COUCHBASE
    • REDIS
    • CAFFEINE
    • SIMPLE
      具体都是哪些,本文不一一讨论,自行Google(因为我只用了redis 😂)

    相关注解

    • EnableCaching 开启注解
    • CacheConfig 类注解 统一配置该类中所有要缓存的数据
    • Cacheable 方法注解 如果从缓存中取到了对应的数据,则直接返回;否则执行方法内的代码,并将返回的数据存入缓存中
    • CachePut 方法注解 无论如何都会执行方法内的代码,并将返回的数据存入缓存中
    • CacheEvict 方法注解 无论如何都会执行方法内的代码,并将返回的数据从缓存中删除
      详细用法可参看spring官方文档, 或者这篇博客

    配置

    spring:
      cache:
        type: redis  #要用的缓存类型
        cache-names: test #默认的缓存名称,如果在对应的cacheName不指定,则会用到该名字
        redis:
          key-prefix:  TEST_ #缓存key的前缀,如果不配置,则会根据cacheNames和key组合为redis的key
          time-to-live:  10m #缓存时间
    

    Talk is cheap, show me code.

    import java.io.Serializable
    import javax.persistence.Entity
    import javax.persistence.Id
    import org.springframework.cache.annotation.Cacheable
    import org.springframework.data.jpa.repository.JpaRepository
    import org.springframework.stereotype.Service
    import org.springframework.web.bind.annotation.*
    import org.slf4j.Logger
    import org.slf4j.LoggerFactory
    
    inline fun <reified T> logger(): Logger {
        return LoggerFactory.getLogger(T::class.java)
    }
    
    @Entity
    data class SysConfig(
            @Id
            var id: Long = 0,
            var key: String? = null,
            var value: String? = null,
            var remark: String? = null,
            var status: Int = 0
    ): Serializable
    
    interface SysConfigRepository : JpaRepository<SysConfig, Long> {
        fun findByKey(key: String): SysConfig?
    }
    
    @Service
    class SysConfigService(val configRepository: SysConfigRepository) {
        val log = logger<SysConfigService>()
        @Cacheable("SYS_CONFIG_DETAIL", key = "#name + '_' + #i")
        fun findByName(name: String, i: Int): SysConfig? {
            log.info("load from db {} {}", name, i)
            return configRepository.findByKey(name)
        }
    
        @Cacheable("SYS_CONFIG_ALL")
        fun all(): List<SysConfig> {
            log.info("load from db")
            return configRepository.findAll()
        }
    }
    
    @RestController
    @RequestMapping("config")
    class SysConfigController(val sysConfigService: SysConfigService) {
    
        @GetMapping("/{name}")
        fun config(@PathVariable("name") name: String,
                   @RequestParam(value = "i", required = false, defaultValue = "0")i: Int) = sysConfigService.findByName(name, i)
    
        @GetMapping("")
        fun config() = sysConfigService.all()
    }
    

    访问对应的url即可去redis中观察

    image.png

    PS:如果有缓存hash需求的可参看我的另外一篇文章《spring-boot-cache之 lettuce VS redisson》

    相关文章

      网友评论

        本文标题:spring-boot-cache应用小结(Redis篇)

        本文链接:https://www.haomeiwen.com/subject/lmtcmqtx.html